原文链接: python 构造xml

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ElementTree
from xml.dom.minidom import parseString
root = ET.Element("root")
doc = ET.SubElement(root, "doc")
ET.SubElement(doc, "field1", name="k1").text = "1<2"
ET.SubElement(doc, "field2", name="k2").text = "2>1"
tree = ET.ElementTree(root)
tree.write("filename.xml")
xml = ElementTree.tostring(root)
print(xml)
prettyxml = parseString(xml).toprettyxml()
print(prettyxml)

输出

1
2
3
4
5
6
7
8
b'<root><doc><field1 name="k1">1&lt;2</field1><field2 name="k2">2&gt;1</field2></doc></root>'
<?xml version="1.0" ?>
<root>
<doc>
<field1 name="k1">1&lt;2</field1>
<field2 name="k2">2&gt;1</field2>
</doc>
</root>

1
2
➜ ~ cat filename.xml
<root><doc><field1 name="k1">1&lt;2</field1><field2 name="k2">2&gt;1</field2></doc></root>%