【问题标题】:Parse xml type file解析xml类型文件
【发布时间】:2018-11-21 20:32:35
【问题描述】:

我有一个 xml 类型的文档:

<configuration>
    <appSettings>
        <add key="title" value="Donny" />
        <add key="updaterApplication" value="Updater v4.3" />
    </appSettings>
</configuration>

我需要修改一个特定的条目,例如value="Updater v4.3"value="Updater v4.4",当添加key="updaterApplication"

我试过了:

import xml.etree.ElementTree as ET

tree = ET.parse(my_file_name)
root = tree.getroot()
tkr_itms = root.findall('appSettings')
for elm in tkr_itms[0]:
    print(elm)
    print(elm.attributes)
    print(elm.value)
    print(elm.text)

但无法处理'&lt; ... /&gt;'之间的内容。

【问题讨论】:

    标签: python xml tags elementtree


    【解决方案1】:

    我看到你发现“''之间的内容”是属性。

    迭代add 元素并检查key 属性值的另一种方法是检查predicate 中的属性值。

    示例...

    Python

    import xml.etree.ElementTree as ET
    
    tree = ET.parse("my_file_name")
    root = tree.getroot()
    root.find('appSettings/add[@key="updaterApplication"]').attrib["value"] = "Updater v4.4"
    
    print(ET.tostring(root).decode())
    

    输出

    <configuration>
        <appSettings>
            <add key="title" value="Donny" />
            <add key="updaterApplication" value="Updater v4.4" />
        </appSettings>
    </configuration>
    

    See here for more info on XPath in ElementTree.

    【讨论】:

      【解决方案2】:

      没关系...:

      import xml.etree.ElementTree as ET
      tree = ET.parse(my_file_name)
      root = tree.getroot()
      for elm in root.iter('add'):
          if elm.attrib['key']=='updaterApplication':
              elm.attrib['value'] = 'Updater v4.4'
          print(elm.attrib)
      

      【讨论】:

        猜你喜欢
        • 2017-02-19
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-12
        • 2017-11-04
        • 2011-11-20
        相关资源
        最近更新 更多