zoukankan      html  css  js  c++  java
  • python使用minidom生成XML文件

    找了蛮多,这篇文章最简单实用

    1.使用minidom创建XML文件

    # -*- coding: cp936 -*-
    """
    使用minidom生成XML
    1.创建Element,createElement
    2.添加子节点,appendChild
    3.创建Text,createTextNode
    4.创建属性,createAttribute
    "
    ""
    from xml.dom import minidom,Node

    # 创建Document
    doc = minidom.Document()
    # 创建book节点
    book = doc.createElement("book")
    doc.appendChild(book)
    # 创建Title节点
    title = doc.createElement("title")
    text = doc.createTextNode("Sample XML Thing")
    title.appendChild(text)
    book.appendChild(title)
    # 创建author节点
    author = doc.createElement("author")
    # 创建name节点
    name = doc.createElement("name")
    first = doc.createElement("first")
    first.appendChild(doc.createTextNode("Benjamin"))
    name.appendChild(first)

    last = doc.createElement("last")
    last.appendChild(doc.createTextNode("Smith"))
    name.appendChild(last)

    author.appendChild(name)
    book.appendChild(author)
    # author节点完毕

    # 创建chapter节点
    chapter = doc.createElement("chapter")
    chapter.setAttribute("number","1")
    title = doc.createElement("title")
    title.appendChild(doc.createTextNode("Fisrt Chapter"))
    chapter.appendChild(title)

    para = doc.createElement("para")
    para.appendChild(doc.createTextNode("I think widgets are great.you should buy lots \
    of them from"
    ))
    company = doc.createElement("company")
    company.appendChild(doc.createTextNode("Springy widgets,Inc"))
    para.appendChild(company)

    chapter.appendChild(para)
    # chapter节点完毕
    book.appendChild(chapter)
    # book节点完毕

    print doc.toprettyxml(indent = " ")

    2.生成的XML文件

    <?xml version="1.0" ?>
    <book>
        <title>
            Sample XML Thing
        </title>
        <author>
            <name>
                <first>
                    Benjamin
                </first>
                <last>
                    Smith
                </last>
            </name>
        </author>
        <chapter number="1">
            <title>
                Fisrt Chapter
            </title>
            <para>
                I think widgets are great.you should buy lots of them from
                <company>
                    Springy widgets,Inc
                </company>

  • 相关阅读:
    spring的断言工具类Assert的基本使用
    开发工具推荐
    IDEA 接口调试插件 HTTP Client
    【笔记0-开篇】面试官系统精讲Java源码及大厂真题
    面试题:HashSet、TreeSet 和HashMap 的实现与原理
    Mybatis面试问题集锦
    分组拼接字符串,GROUP_CONCAT
    跨表更新,Mysql Update Join
    【设计模式】UML类图及Java的类之间的关系
    Sql性能优化梳理
  • 原文地址:https://www.cnblogs.com/UnGeek/p/2861396.html
Copyright © 2011-2022 走看看