2015-01-04 100 views
1

如何在Python中使用以下XML来更改国家“Liechtenstein”的“年”值?我引用Python's XML Element TreePython XML元素替换

<?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> 

回答

3

可以使用文本方法是这样的:

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" 

希望这会有所帮助。

+0

感谢您的帮助Anzel – Taewan

+0

@Taewan,不是问题,我很高兴它有帮助。作为一个方面说明,你可能想要查看[lxml](http://lxml.de/),它具有更强大的** xpath **支持和更好的性能:) – Anzel

+0

我有一个非常类似的问题题。你介意看看它? http://stackoverflow.com/questions/27773141/xml-arg-value-replacement-in-python – Taewan