简体   繁体   English

我想用python替换XLM的值

[英]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: 笔记:

  • I have used lxml to parse and to modify the XML object _ I iterate through each element using the for loop 我使用lxml来解析和修改XML对象_我使用for循环迭代每个元素
  • I check if the element is a property element and also if it has a name attribute whose value is country 我检查元素是否是property元素,以及它是否具有值为countryname属性
  • If so then have changed it's value to Africa 如果是这样,那么就改变了它对非洲的价值
  • This code is in Python 2.+ 此代码在Python 2 +中

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

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