import 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
写入到文件
tree = ET.ElementTree(root)
tree.write("output.xml", encoding="utf-8", xml_declaration=True) #保存时无缩进,添加缩进需要借用dom
带缩进地写入到文件
import 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)