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)123456789101112131415161718
輸出
b'<root><doc><field1 name="k1">1<2</field1><field2 name="k2">2>1</field2></doc></root>'<?xml version="1.0" ?><root>
<doc>
<field1 name="k1">1<2</field1>
<field2 name="k2">2>1</field2>
</doc></root>12345678
~ cat filename.xml<root><doc><field1 name="k1">1<2</field1><field2 name="k2">2>1</field2></doc></root>%