【问题标题】:write XML subtree to file将 XML 子树写入文件
【发布时间】:2014-10-15 14:53:58
【问题描述】:

所以我有一个巨大的 XML 文件,但只希望它的一部分在另一个文件中。因此我想提取它,然后我可以在不影响原始文件的情况下对其进行一些工作。

这是基本思路

<a>
      <otherethings> </otherthings>
      <b>
          <things> </thing>
      </b>
      <otherethings2></otherthings2>
</a>

简单地说我想把b解压到另一个文件并编辑它

在python中如何实现

我目前正在尝试使用xml.etree.ElementTree

但似乎无法正确处理。

根据要求我的错误

1.

    tree = ET.parse('Data.xml')
    root = tree.getroot()
    rootelement = root.iter('b')
    tree._setroot(rootelement)
    root = tree.getroot()
    tree.write('Data2.xml')

2.

tree = ET.parse('Data.xml', 'b')
root = tree.getroot()
tree.write('Data2.xml')

老实说,我只是在猜测

不要误会我的意思,我确实在网上查过,但找不到任何东西。

【问题讨论】:

  • 你能贴出你的代码吗?
  • 老实说,我认为这不会有帮助,因为它完全不起作用,但我尝试了几件事。这是一对。
  • 看看这些链接:lxml.de(类似但比 elementtree 更好)或crummy.com/software/BeautifulSoup/bs4/doc 我个人最喜欢的,因为它真的很容易使用

标签: python xml xml.etree


【解决方案1】:

这应该可以。

from xml.etree import ElementTree as ET

tree = ET.parse('Data.xml')
for el in tree.iter('b'):
    towrite = ET.ElementTree(el)
    towrite.write('Data2.xml')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多