【问题标题】:Modify a XML using ElementTree使用 ElementTree 修改 XML
【发布时间】:2014-09-23 23:20:16
【问题描述】:
<grandParent>
    <parent>
       <child>Sam/Astronaut</child>
    </parent>
</grandParent>

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

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

这是修改xml文件的正确方法吗?有更好的办法吗?或者在上面的代码中我还应该注意什么?

【问题讨论】:

  • 你运行了那个代码吗?结果如何?
  • 当我现在运行此代码时,我没有看到 XML 被修改。我以为我确实看到它早些时候被修改了,并且我收到了所需的结果,但认为它的方式不正确,因此发布了。
  • 当您提出关于 SO 的问题时,最好包含所有相关信息,包括您发布的任何代码的预期和观察结果。否则,问得好。
  • 好的队长!会记住这一点。

标签: python xml xml-parsing elementtree celementtree


【解决方案1】:

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

试试这个:

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

如果你想搜索一个特定的孩子,你可以这样做:

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() 方法。

【讨论】:

  • 感谢这项工作。我想我可以使用 find() 来验证不存在与我即将进入的孩子相似的孩子。避免重复。
  • 其实如何在父标签里面执行find命令呢?两个父标签可以有相同的子标签,但一个父标签不应该有重复..
  • 对我有用。这可能是我从 ElementTree 需要的全部内容。如果我想我需要更多功能,我会研究 lxml.etree。非常感谢!
  • 好吧,我想我说得太早了——我现在在父标​​签中有命名空间,我的 find all 方法现在有问题... AttributeError: 'NoneType' object has no attribute 'findall'我该如何处理?
  • 我正在做这样的事情。 space={'xmlns':'maven.apache.org/POM/4.0.0', 'xsi':'w3.org/2001/XMLSchema-instance', 'schemaLocation':'maven.apache.org/xsd/maven-4.0.0.xsd'} 在 find all 方法中使用空格.. find all('module', namespaces =空格)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-06
  • 2021-02-06
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多