【问题标题】:How to change a specific value of an xml file using python如何使用python更改xml文件的特定值
【发布时间】:2020-02-06 10:10:06
【问题描述】:

我有一个 XML 文件,其结构类似于:

<config>
    <property>
        <name>prop1</name>
        <value>1</value>
    </property>
    <property>
        <name>prop2</name>
        <value>2</value>
    </property>
    <property>
        <name>prop3</name>
        <value>3</value>
    </property>
    <property>
        <name>prop4</name>
        <value>4</value>
    </property>
</config>

如何使用 python xml.etree.ElementTree 将 prop3 的值更改为 10?

【问题讨论】:

  • 有什么问题?你有没有尝试过?

标签: python xml elementtree


【解决方案1】:

见下文。
(无需遍历所有元素 - 使用 'find' 方法并直接指向要修改的元素。也无需使用外部库。)。

import xml.etree.ElementTree as ET


xml = '''<config>
    <property>
        <name>prop1</name>
        <value>1</value>
    </property>
    <property>
        <name>prop2</name>
        <value>2</value>
    </property>
    <property>
        <name>prop3</name>
        <value>3</value>
    </property>
    <property>
        <name>prop4</name>
        <value>4</value>
    </property>
</config>'''

root = ET.fromstring(xml)
prop3 = root.find(".//property/[name='prop3']")
prop3_val = prop3.find('value')
print(prop3_val.text)
prop3_val.text = 10
print(prop3_val.text)

输出

3
10

【讨论】:

    【解决方案2】:

    您可以执行以下操作(只需查看 lxml 文档)。

    import lxml.etree as ET
    
    file = "file.xml"
    
    # Grab the root (config node)
    root = ET.parse(file).getroot()
    
    # Grab all 'property' nodes
    properties = root.findall("property")
    
    # Iterate over them
    for property in properties:
      # Find the property with name 'prop3'
      if property.find("name").text == "prop3":
        # Update the value to ten
        property.find("value").text = "10"
    
    # Write back the modified file
    with open(file, "w") as f:
      f.write(ET.tostring(root, encoding="unicode"))
    

    奖励,您可以将最后一行更改为 f.write(ET.tostring(root, encoding="unicode", pretty_print=True)) 以获得带有缩进和返回的漂亮 XML 文件。

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多