zoukankan      html  css  js  c++  java
  • dom写xml

    1.引入包

    import xml.dom.minidom

    2.writexml方法

    writexml(writer, indent, addindent, newl, encoding)

    writer是文件对象。
    indent是每个tag前填充的字符,如:' ',则表示每个tag前有两个空格。
    addindent是每个子结点的缩近字符,如下面的例子中单引号中我直接用的tab键。
    newl是每个tag后填充的字符,如:' ',则表示每个tag后面有一个回车
    encoding是生成的XML信息头中的encoding属性值,在输出时minidom并不真正进行编码的处理,如果你保存的文本内容中有汉字,则需要自已进行编码转换。

    3.直接上python代码

    #xmlTest_write.py
    # -*- coding: utf-8 -*-
    
    import xml.dom.minidom
    
    #生成xml文件
    def GenerateXml():
        impl = xml.dom.minidom.getDOMImplementation()
        #设置根结点emps
        dom = impl.createDocument(None, 'emps', None)
        root = dom.documentElement
    
        employee = dom.createElement('emp')
        #增加属性
        employee.setAttribute("empno","1111")
        root.appendChild(employee)
    
        #设置子结点
        #ename
        nameE=dom.createElement('ename')
        nameT=dom.createTextNode('杰克')
        nameE.appendChild(nameT)
        #子节点添加属性
        nameE.setAttribute("lastname","")
        employee.appendChild(nameE)
    
        #age
        nameE=dom.createElement('age')
        nameT=dom.createTextNode('33')
        nameE.appendChild(nameT)
        employee.appendChild(nameE)
    
        f= open('emplist.xml', 'w') #w替换为a,追加
        dom.writexml(f, addindent=' ', newl='
    ')
        f.close()
    
    GenerateXml()

    4.运行结果,生成的emplist.xml文件。

    <?xml version="1.0" ?>
      <emps>
        <emp empno="1111">
          <ename lastname="克">杰克</ename>
          <age>33</age>
        </emp>
      </emps>
  • 相关阅读:
    docker相关资源监控采集方法整理
    三节课MINI计划第四周
    三节课MINI计划第五周
    三节课MINI计划第四周
    三节课MINI计划第三周
    三节课MINI计划第二周
    Bilibili用户需求分析报告
    三节课MINI计划第一周
    《产品思维30讲 》学习笔记
    PHP-FPM未授权访问漏洞
  • 原文地址:https://www.cnblogs.com/eustoma/p/9581749.html
Copyright © 2011-2022 走看看