使用ElementTree修改XML [英] Modify a XML using ElementTree

查看:374
本文介绍了使用ElementTree修改XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想通过在父标记内添加另一个子标记来修改上述XML.我正在做这样的事情.

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")

这是修改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?

推荐答案

您的代码创建了一个全新的树并将Jay添加到其中.您需要将Jay连接到现有树,而不是新树.

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.

尝试一下:

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")

注意a.findall()(类似于a.find(),但返回所有命名元素). xml.etree具有非常个受限的搜索条件.您可能会考虑使用lxml.etree及其.xpath()方法.

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.

这篇关于使用ElementTree修改XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆