• 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>

  • 相关阅读:
    iOS UIActivityIndicatorView 的使用(旋转菊花)
    iOS textView的使用总结
    IOS UI -label总结
    cocos2dx常见的46中+22中动作详解
    iOS 第三方框架SDWebImage的简单使用
    iOS 下拉刷新
    OC 字符串操作
    一些iOS常用的第三方库和控件
    标日语法(1)
    面向对象(初级)个人总结 第二部分 封装
  • 原文地址:https://www.cnblogs.com/UnGeek/p/2861396.html
Copyright © 2020-2023  润新知