import xml.dom.minidom as minidom
xml = minidom.Document()
root = xml.createElement("root")
xml.appendChild(root)
doc = xml.createElement("doc")
doc.setAttribute("location", "one")
root.appendChild(doc)
field = xml.createElement("field1")
field.setAttribute("name", "blah")
text = xml.createTextNode("some value1")
field.appendChild(text)
doc.appendChild(field)
field = xml.createElement("field2")
field.setAttribute("name", "asdfasd")
text = xml.createTextNode("some value2")
field.appendChild(text)
doc.appendChild(field)
print(xml.toprettyxml(indent=' '*4))
收益率
^{pr2}$
或者,如果您喜欢使用ElementTree方法来创建XML,并且不介意的话
由于效率有点低,可以使用ElementTree来编写未格式化的XML
到StringIO(对于Python2)或ByteIO(对于Python3),将其解析为一个minidom
文档,然后使用toprettyxml再次将其写回:import xml.etree.cElementTree as ET
import xml.dom.minidom as minidom
try:
# for Python2
from cStringIO import StringIO as BytesIO
except ImportError:
# for Python3
from io import BytesIO
root = ET.Element("root")
doc = ET.SubElement(root, "doc", location="one")
ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"
buf = BytesIO()
buf.write(ET.tostring(root))
buf.seek(0)
root = minidom.parse(buf)
print(root.toprettyxml(indent=' '*4))