简体   繁体   中英

How to modify the value under a designate path with python?

There is a xml file like below:

<aa>
  <bb>BB</bb>
    <cc>
      <dd>Tom</dd>
    </cc>
    <cc>
      <dd>David</dd>
    </cc>
</aa>

I'm trying to modify the value "Tom" and "David", but I can't get any value in <dd> . Then I try to get the value in <bb> , but I got the response "None" from my code. My code as below:

import xml.etree.ElementTree as ET

tree = ET.parse("abc.xml")
root = tree.getroot()
a = root.find('aa/bb')
print(a)

Does someone could help me to correct my code to get and modify the value of <dd> ? Many thanks.

Your top level object is aa . So root is element aa

To get bb , just do root.find('bb')

>>> root
<Element 'aa' at 0x7fb1df5f0278>
>>> a = root.find('bb')
>>> a
<Element 'bb' at 0x7fb1df5f0228>

So to edit the names, try something like this

for dd in root.findall('cc/dd'):
    if dd.text in ["Tom", "David"]:
        dd.text = "something else"

Using ElementTree

Demo:

import xml.etree.ElementTree
et = xml.etree.ElementTree.parse(filename)
root = et.getroot()

for cc in root.findall('cc'):          #Find all cc tags
    print(cc.find("dd").text)          #Print current text
    cc.find("dd").text = "NewValue"    #Update dd tags with new value

et.write(filename)                     #Write back to xml

If you don't mind using BeautifulSoup , you can modify your XML through it:

data = """<aa>
  <bb>BB</bb>
    <cc>
      <dd>Tom</dd>
    </cc>
    <cc>
      <dd>David</dd>
    </cc>
</aa>"""


from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'xml')

for dd in soup.select('cc > dd'):   # using CSS selectors
    dd.clear()
    dd.append('XXX')

print(soup.prettify())

Output:

<?xml version="1.0" encoding="utf-8"?>
<aa>
 <bb>
  BB
 </bb>
 <cc>
  <dd>
   XXX
  </dd>
 </cc>
 <cc>
  <dd>
   XXX
  </dd>
 </cc>
</aa>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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