簡體   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