Python
pythonimport xml.etree.ElementTree as ET
from xml.etree.ElementTree import tostring
from xml.etree.ElementTree import Element
from io import BytesIO
root = Element("tag")
child = Element("child1", attrib={"jh": "123", "oi": "12312"})
child.text="dasd"
child2 = Element("child2", attrib={"jh": "123"})
child2.text="dasd"
root.append(child)
root.append(child2)
# print(tostring(root, encoding='utf8', method='xml').decode())
et = ET.ElementTree(root)
f = BytesIO()
et.write(f, encoding='utf-8', xml_declaration=True)
print(f.getvalue().decode()) # your XML file, encoded as UTF-8
写入到文件
pythontree = ET.ElementTree(root)
tree.write("output.xml", encoding="utf-8", xml_declaration=True) #保存时无缩进,添加缩进需要借用dom
带缩进地写入到文件
pythonimport xml.etree.ElementTree as ET
from xml.dom import minidom
def saveXML(root, filename, indent="\t", newl="\n", encoding="utf-8"):
rawText = ET.tostring(root)
dom = minidom.parseString(rawText)
with open(filename, 'w') as f:
dom.writexml(f, "", indent, newl, encoding)
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!