开发者社区> 问答> 正文

如何用python生成xml

如何用python生成xml

展开
收起
保持可爱mmm 2019-12-11 14:31:45 439 0
1 条回答
写回答
取消 提交回答
  • xml.dom.minidom模块实现创建一个XML文档。

    创建XML的过程

    1、内存数据产生

    2、产生xml内存对象(也就是DOM树)

    3、产生根对象

    4、往根对象里加数据

    5、把xml内存对象写到文件

    下面是一个创建xml文档的简单实例:

    import xml.dom.minidom

    #在内存中创建一个空的文档

    doc = xml.dom.minidom.Document()

    #创建一个根节点Managers对象

    root = doc.createElement('Managers')

    #设置根节点的属性

    root.setAttribute('company', 'xx科技')

    root.setAttribute('address', '科技软件园')

    #将根节点添加到文档对象中

    doc.appendChild(root)

    managerList = [{'name' : 'joy', 'age' : 27, 'sex' : '女'},

    {'name' : 'tom', 'age' : 30, 'sex' : '男'},

    {'name' : 'ruby', 'age' : 29, 'sex' : '女'}

    ]

    for i in managerList :

    nodeManager = doc.createElement('Manager')

    nodeName = doc.createElement('name')

    #给叶子节点name设置一个文本节点,用于显示文本内容

    nodeName.appendChild(doc.createTextNode(str(i['name'])))

    nodeAge = doc.createElement("age")

    nodeAge.appendChild(doc.createTextNode(str(i["age"])))

    nodeSex = doc.createElement("sex")

    nodeSex.appendChild(doc.createTextNode(str(i["sex"])))

    #将各叶子节点添加到父节点Manager中,

    #最后将Manager添加到根节点Managers中

    nodeManager.appendChild(nodeName)

    nodeManager.appendChild(nodeAge)

    nodeManager.appendChild(nodeSex)

    root.appendChild(nodeManager)

    #开始写xml文档

    fp = open('c:\wcx\Manager.xml', 'w')

    doc.writexml(fp, indent='\t', addindent='\t', newl='\n', encoding="utf-8")

    执行结果:

    joy

    27

    tom

    30

    ruby

    29

    用Python自带的写xml文档的API去写,比较方便,后期容易维护。如果直接用打开文件的方式,一行一行的去写,比较费时,也难以维护。

    xml.dom模块创建xml的部分API

    minidom.Document()

    创建一个空白xml文档树对象。

    每个xml文档都是一个Document对象,代表着内存中的DOM树。

    doc. createElement(tagName)

    生成xml文档节点。参数表示要生成节点的名称。

    如:(注意这里使用的例子都来自于上面创建xml文档的程序中,下同)

    #创建一个根节点Managers对象

    root = doc.createElement('Managers')

    node.setAttribute(attname, value)

    给节点添加属性值对(Attribute)。

    参数说明:

    attname :属性的名称

    value :属性的值

    如:

    设置根节点的属性:

    root.setAttribute('company', 'xx科技')

    doc.createTextNode(data)

    给叶子节点添加文本节点。如:

    #给叶子节点name设置一个文本节点,用于显示文本内容

    nodeName.appendChild(doc.createTextNode(str(i['name'])))

    node.appendChild(node1)

    将节点node1t添加到节点node下。如:

    #将叶子节点nodeName添加到父节点nodeManager下

    nodeManager.appendChild(nodeName)

    doc. writexml()

    函数原型:

    writexml(writer, indent='', addindent='', newl='', encoding=None)

    将内存中xml文档树写入文件中。

    参数说明:

    writer :要写的目标文件的文件对象。

    indent :

    fp = open('c:\Manager.xml', 'w')

    doc.writexml(fp, indent='', addindent='\t', newl='\n', encoding="utf-8") 问题来源于python学习网

    2019-12-11 14:32:03
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载