[英]Beautify xml in Python eTree
我有这个简单的py脚本,可以制作一个xml文件并保存,并且想知道是否有一种简单的方式来缩进它?
import xml.etree.cElementTree as ET
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"
我看过其他一些SO Q&A的Python中的漂亮打印XML,但这些似乎大多需要其他外部库? 并想知道是否有一种方法不使用那些?
谢谢您的帮助。
您可以使用标准库的minidom模块的toprettyxml
方法 :
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))
产量
<?xml version="1.0" ?>
<root>
<doc location="one">
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
或者,如果您更喜欢使用ElementTree
方法创建XML,并且不介意效率低下,则可以使用ElementTree
将未格式化的XML写入StringIO (对于Python2)或ByteIO (对于Python3),然后将其解析为一个小型文档,然后使用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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.