先说说如何创建一个XML文件吧
# -*- coding: utf-8 -*-from xml.dom import minidomimpl = minidom.getDOMImplementation()dom = impl.createDocument(None, None, None)#namespaceURI, qualifiedName, doctype#write to domroot = dom.createElement("skills")for skillid in range(10): skill= dom.createElement('skill') skill.setAttribute('id', str(skillid)) root.appendChild( skill )dom.appendChild( root )#end write to dom#writexml(writer, indent, addindent, newl, encoding)#writer是文件对象#indent是每个tag前填充的字符,如:' ',则表示每个tag前有两个空格#addindent是每个子结点的缩近字符#newl是每个tag后填充的字符,如:'n',则表示每个tag后面有一个回车#encoding是生成的XML信息头中的encoding属性值,# 在输出时minidom并不真正进行编码的处理,如果你保存的文本内容中有汉字,# 则需要自已进行编码转换。f=file('c:\skills.xml','w')dom.writexml(f,'',' ','n','utf-8')f.close()
这样生成的XM了如下:
<?xml version="1.0" encoding="utf-8"?>
<skills>
<skill id="0"/>
<skill id="1"/>
<skill id="2"/>
<skill id="3"/>
<skill id="4"/>
<skill id="5"/>
<skill id="6"/>
<skill id="7"/>
<skill id="8"/>
<skill id="9"/>
</skills>
#######################
读取XML
>>> dom = xml.dom.minidom.parse('c:/skills.xml')
>>> root = dom.documentElement
>>> root.nodeName
>>> r2.nodeName
u'skills'