繁体   English   中英

我想用python替换XLM的值

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

笔记:

  • 我使用lxml来解析和修改XML对象_我使用for循环迭代每个元素
  • 我检查元素是否是property元素,以及它是否具有值为countryname属性
  • 如果是这样,那么就改变了它对非洲的价值
  • 此代码在Python 2 +中

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM