<property name="country">India</property>
<property name="city">Bangalore</property>
我想按密钥名称进行搜索,以及属性名称是否为国家/地区。我必须用非洲替换这个值,结果应如下所示。
<property name="country">Africa</property>
<property name="city">Bangalore</property>
答案 0 :(得分:2)
xml_example.xml文件
<root_1>
<property name="country">India</property>
<property name="city">Bangalore</property>
</root_1>
<强>码强>
import xml.etree.ElementTree as ET
tree = ET.parse("xml_example.xml")
for property in tree.iter('property'):
if property.attrib['name'] == "country" and property.text == "India":
property.text = "Africa"
tree.write("xml_example.xml")
<强>输出:强>
<root_1>
<property name="country">Africa</property>
<property name="city">Bangalore</property>
</root_1>
答案 1 :(得分:1)
<强>代码:强>
from lxml import etree as xml
xml_str="""
<note>
<property name="country">India</property>
<property name="city">Bangalore</property>
</note>
"""
xm=xml.fromstring(xml_str)
for a in xm.iter():
if a.tag == "property" and a.attrib.get("name") == "country":
a.text = "Africa"
print xml.tostring(xm)
<强>输出:强>
<note>
<property name="country">Africa</property>
<property name="city">Bangalore</property>
</note>
备注:强>
property
元素,以及它是否具有name
属性,其值为country