我有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>
答案 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>