我想用python替换XLM的值

时间:2015-12-14 06:52:43

标签: python xml parsing xml-parsing

<property name="country">India</property>
<property name="city">Bangalore</property>

我想按密钥名称进行搜索,以及属性名称是否为国家/地区。我必须用非洲替换这个值,结果应如下所示。

<property name="country">Africa</property>
<property name="city">Bangalore</property>

2 个答案:

答案 0 :(得分:2)

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>

答案 1 :(得分: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元素,以及它是否具有name属性,其值为country
  • 如果是,那么将其价值改为非洲
  • 此代码在Python 2。+