zoukankan      html  css  js  c++  java
  • 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='	', addindent='	', newl='
    ')
    
  • 相关阅读:
    2月4日进度
    每日总结3-6
    每日总结3-5
    每日总结3-4
    每日总结3-2
    本周计划
    本周计划
    假期每日总结2-13
    假期每日总结2-12
    假期每日总结2-11
  • 原文地址:https://www.cnblogs.com/iFanLiwei/p/13597749.html
Copyright © 2011-2022 走看看