[英]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.