[英]How do I output an XML file using ElementTree in python?
I'm slightly confused about writing an xml file using the xml ElementTree module. 我对使用xml ElementTree模块编写xml文件感到有些困惑。 I tried to build the document: eg 我试图构建文档:例如
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
How do I exactly take this, and write it to a file? 我如何完全接受这个,并将其写入文件?
Create an instance of ElementTree
class and call write()
: 创建ElementTree
类的实例并调用write()
:
class xml.etree.ElementTree.ElementTree(element=None, file=None)
ElementTree wrapper class. ElementTree包装类。 This class represents an entire element hierarchy, and adds some extra support for serialization to and from standard XML . 此类表示整个元素层次结构,并为标准XML的序列化添加了一些额外的支持 。
element is the root element. element是根元素。 The tree is initialized with the contents of the XML file if given. 如果给定,则使用XML文件的内容初始化树。
tree = ET.ElementTree(a)
tree.write("output.xml")
You can write xml using ElementTree.write()
function - 你可以使用ElementTree.write()
函数编写xml -
import xml.etree.ElementTree as ET
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
ET.ElementTree(a).write("test.xml")
This would write to file - test.xml
- 这将写入文件 - test.xml
-
<a><b /><c><d /></c></a>
To write xml with indents and elements on newline , you can use - xml.dom.minidom.toprettyxml
. 要在换行符上使用缩进和元素编写xml,可以使用 - xml.dom.minidom.toprettyxml
。 Example - 示例 -
import xml.etree.ElementTree as ET
import xml.dom.minidom as md
a = ET.Element('a')
b = ET.SubElement(a, 'b')
c = ET.SubElement(a, 'c')
d = ET.SubElement(c, 'd')
xmlstr = ET.tostring(a).decode()
newxml = md.parse(xmlstr)
newxml = md.parseString(xmlstr)
with open('test.xml','w') as outfile:
outfile.write(newxml.toprettyxml(indent='\t',newl='\n'))
Now, test.xml
would look like - 现在, test.xml
看起来像 -
<?xml version="1.0" ?>
<a>
<b/>
<c>
<d/>
</c>
</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.