Python XML 元素替换

Python XML Element Replacement

如何在 Python 中更改以下 XML 中国家 "Liechtenstein" 的 "year" 值?我正在引用 Python's XML Element Tree

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
    </country>
</data>

您可以像这样使用 text 方法:

import xml.etree.ElementTree as ET

s = '''<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
    </country>
</data>'''

tree = ET.fromstring(s)

# I use iterfind, you can use whatever method to locate this node
for node in tree.iterfind('.//country[@name="Liechtenstein"]/year'):
    # this will alter the "year"'s text to '2015'        
    node.text = '2015' # Please note it has to be str '2015', not int like 2015

print ET.tostring(tree)

结果:

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2015</year>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
    </country>
</data>

如果要更改节点的属性,请像这样使用set

for node in tree.iterfind('.//country[@name="Liechtenstein"]/year'):
    node.set('updated', 'yes') # key, value pair for updated="yes"

希望对您有所帮助。