使用python在xml文件中设置或获取某个元素

时间:2015-05-18 06:12:46

标签: python xml

我有xml文件,如下所示,下面的脚本我可以用(root.iter)更改任何特定元素国家/地区的值。如何修改特定neighbor的{​​{1}}值,例如第一个或第二个?

country

代码

<data>
    <country name="vers1" value="1"> (can change its value with below script)
     <neighbor name="test" value="E"/> (how to change its value?????)
    </country>
    <country name="vers2" value="2">
     <neighbor name="test" value="N"/>
    </country>
    <country name="vers3" value="3">
     <neighbor name="test" value="W"/>
    </country>
</data>

1 个答案:

答案 0 :(得分:0)

使用 xpath 从xml获取目标标记:

<强>演示

#Change value of neighbor for  vers2 country , 
import xml.etree.ElementTree as ET

#tree = ET.parse('test.xml')
root = ET.fromstring(data)
neighbors = root.findall("country[@name='vers2']/neighbor[@name='test']")
for i in neighbors:
    i.attrib["value"] = "changed"

print "Output:", ET.tostring(root)    

<强>输出

Output: <data>
    <country name="vers1" value="1"> (can change its value with below script)
     <neighbor name="test" value="E" /> (how to change its value?????)
    </country>
    <country name="vers2" value="2">
     <neighbor name="test" value="changed" />
    </country>
    <country name="vers3" value="3">
     <neighbor name="test" value="W" />
    </country>
</data>