你可以使用標準庫的minidom模塊的toprettyxml
method:
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),解析成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))
'minidom'是在標準庫。您可以使用'minidom'來創建文檔,然後調用它的'toprettyxml'方法。 – unutbu
我看不到該腳本「如何製作xml文件並保存」它。保存文件的代碼在哪裏? –
@Robᵩ對不起,我忘了包括保存 –