Python网络编程基础笔记-使用minidom生成XML文件


1.使用minidom创建XML文件

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

 res = minidom.Document()
    query = res.createElement("queryItems")
    query.setAttribute('xmlns:xsi','http://www.w3.org/2001/XMLSchema-instance')
    query.setAttribute('xsi:schemaLocation','http://www.taobao.com/schema/personalhomepage queryItems.xsd')
    query.setAttribute('xmlns','http://www.xxx.com/schema/personalhomepage')
    query.setAttribute('xmlns:header','http://www.xxx.com/schema/personalhomepage/extend/headerType')

"""
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文件

<?xmlversion="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>
        </para>
    </chapter>
</book>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值