Home  >  Article  >  Backend Development  >  python xml reading and writing

python xml reading and writing

高洛峰
高洛峰Original
2016-10-19 16:38:001753browse

先说说如何创建一个XML文件吧

# -*- coding: utf-8 -*-
from xml.dom import minidom
impl = minidom.getDOMImplementation()
dom = impl.createDocument(None, None, None)#namespaceURI, qualifiedName, doctype
#write to dom
root = 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

>>> dom = xml.dom.minidom.parse('c:/skills.xml')

>>> root = dom.documentElement

>>> root.nodeName

>>> r2.nodeName

u'skills'


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn