Python XML元素替换

时间:2015-01-04 21:04:17

标签: python xml parsing replace

如何在Python中使用以下XML更改国家/地区“Liechtenstein”的“年份”值?我引用了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>

1 个答案:

答案 0 :(得分:3)

您可以使用 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>

如果您想更改节点的属性,请使用设置,如下所示:

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

希望这有帮助。