Modify a XML using ElementTree

半腔热情 提交于 2019-12-11 10:08:35

问题


<grandParent>
    <parent>
       <child>Sam/Astronaut</child>
    </parent>
</grandParent>

I want to modify the above XML by adding another child tag inside parent tag. I'm doing something like this..

tree = ET.parse("test.xml")
a=ET.Element('parent')
b=ET.SubElement(a,"child")
b.text="Jay/Doctor"
tree.write("test.xml")

Is this the correct way of modifying the xml file? Any better way? or what else should I be taking care of in the above code?


回答1:


Your code creates a whole new tree and adds Jay to it. You need to connect Jay to the existing tree, not to a new one.

Try this:

import xml.etree.ElementTree as ET

tree = ET.parse("test.xml")
a = tree.find('parent')          # Get parent node from EXISTING tree
b = ET.SubElement(a,"child")
b.text = "Jay/Doctor"
tree.write("test.xml")

If you want to search for a particular child, you could do this:

import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
a = tree.find('parent')
for b in a.findall('child'):
    if b.text.strip() == 'Jay/Doctor':
        break
else:
    ET.SubElement(a,"child").text="Jay/Doctor"
tree.write("test.xml")

Notice a.findall() (similar to a.find(), but returns all of the named elements). xml.etree has very limited search criteria. You might consider using lxml.etree and its .xpath() method.



来源:https://stackoverflow.com/questions/25068629/modify-a-xml-using-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!