[英]I Want to replace a value of XLM Using python
<property name="country">India</property>
<property name="city">Bangalore</property>
I want to search by the key name and if the property name is country. 我想按密钥名称搜索,如果属性名称是国家/地区。 I have to replace the value by Africa and the result should look like below. 我必须替换非洲的价值,结果应如下所示。
<property name="country">Africa</property>
<property name="city">Bangalore</property>
xml_example.xml file xml_example.xml文件
<root_1>
<property name="country">India</property>
<property name="city">Bangalore</property>
</root_1>
code: 码:
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")
Output: 输出:
<root_1>
<property name="country">Africa</property>
<property name="city">Bangalore</property>
</root_1>
Code: 码:
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)
Output: 输出:
<note>
<property name="country">Africa</property>
<property name="city">Bangalore</property>
</note>
Notes: 笔记:
property
element and also if it has a name
attribute whose value is country
我检查元素是否是property
元素,以及它是否具有值为country
的name
属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.