【问题标题】:Dump elementtree into xml file将元素树转储到 xml 文件中
【发布时间】:2014-09-15 20:56:22
【问题描述】:

我用这样的东西创建了一个 xml 树

top = Element('top')
child = SubElement(top, 'child')
child.text = 'some text'

如何将其转储到 XML 文件中?我试过top.write(filename),但是方法不存在。

【问题讨论】:

  • 你为什么要猜测语法?你读过the docs吗?

标签: python xml elementtree


【解决方案1】:

你需要实例化一个ElementTree对象并调用write()方法:

import xml.etree.ElementTree as ET

top = ET.Element('top')
child = ET.SubElement(top, 'child')
child.text = 'some text'

tree = ET.ElementTree(top)
tree.write('output.xml')

运行代码后output.xml的内容:

<top><child>some text</child></top>

【讨论】:

  • @Bob:你需要一个 ElementTree 实例的原因是“这个类代表了整个元素层次结构,并添加了一些额外的对序列化的支持到标准 XML 和来自标准 XML。 " (添加斜体。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多