Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26267381
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Python/Ruby

2009-12-29 11:09:53

.使用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>
        </para>
    </chapter>
</book>

阅读(1439) | 评论(3) | 转发(0) |
0

上一篇:程序员高薪之路

下一篇:比较少见的函数

给主人留下些什么吧!~~

chinaunix网友2009-12-30 22:54:34

一定要将DOM解析XML的方法弄透!

chinaunix网友2009-12-29 12:00:26

http://www.devshed.com/c/a/Python/Parsing-XML-with-SAX-and-Python/2/

hkebao2009-12-29 11:10:25

The Cathedral & the Bazaar Eric S. Raymond Making TeX Work Norman Walsh Python的标准模块里包含了xml 处理的module。我们这次用的是xml.dom.minidom,一个迷你版的DOM API 代码: #! /usr/bin/python import xml.dom.minidom from xml.dom.minidom import Node doc = xml.dom.minidom.parse("boo