【问题标题】:I Want to replace a value of XLM Using python我想用 python 替换 XLM 的值
【发布时间】:2015-12-14 06:52:42
【问题描述】:
<property name="country">India</property>
<property name="city">Bangalore</property>

我想按键名和属性名是否为国家/地区进行搜索。我必须将值替换为非洲,结果应如下所示。

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

【问题讨论】:

  • 你想用属性name="country" to Africa替换所有元素
  • 是的。我想用那个名字搜索并替换它的值。

标签: python xml parsing xml-parsing


【解决方案1】:

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>

【讨论】:

    【解决方案2】:

    代码:

    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.+ 中

    【讨论】:

    • 我正在使用 python 2。它在 xm=lxml.etree.fromstring(xml_str) 中给出如下第 8 行的错误: 'module' object has no attribute 'etree'
    • @AkhilP 你能打印 dir(lxml)
    • @VigneshKalay 显示错误,例如未定义名称“lxml”
    • 你用的是什么版本的python
    • @VigneshKalay python 2.7
    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多