[英]I Want to replace a value of XLM Using python
<property name="country">India</property>
<property name="city">Bangalore</property>
我想按密钥名称搜索,如果属性名称是国家/地区。 我必须替换非洲的价值,结果应如下所示。
<property name="country">Africa</property>
<property name="city">Bangalore</property>
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>
码:
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
元素,以及它是否具有值为country
的name
属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.