python 创建XML

from xml.dom.minidom import Document

# 创建Dom
doc = Document()
# 创建一个根节点
root = doc.createElement("root")
doc.appendChild(root)
# 给根节点添加属性
root.setAttribute("class", "三年二班")
# 给根节点添加子节点
datas = [
    {"name": "小明", "age": 10},
    {"name": "小红", "age": 11},
    {"name": "小刚", "age": 12},
]

for data in datas:
    node = doc.createElement("student")
    node.setAttribute("age", str(data['age']))
    node.appendChild(doc.createTextNode(data["name"]))
    root.appendChild(node)
# 给子节点添加子节点
# 输出为字符串
print(doc.toxml(encoding="utf-8"))
# 输出为文件
with open("aa.xml", "w", encoding="utf-8") as f:
    doc.writexml(f, encoding="utf-8", indent='\t', addindent='\t', newl='\n')
posted @ 2020-09-01 18:23  呓语i  阅读(290)  评论(0编辑  收藏  举报