Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > Python网络爬虫

Python使用minidom读写xml的方法

来源:中文源码网    浏览:194 次    日期:2024-05-10 20:54:26
【下载文档:  Python使用minidom读写xml的方法.txt 】


Python使用minidom读写xml的方法
本文实例讲述了Python使用minidom读写xml的方法。分享给大家供大家参考。具体分析如下:
一 python提供的xml支持
2种工业标准的xml解析方法-SAX和DOM。SAX(simple API for XML),是基于事件处理的,当XML文档顺序地读入时,每次遇到一个元素会触发相应的事件处理函数来处理。DOM(Document Object Model),通过构建一个树结构来表现整个xml文档,一旦树被构建,可以通过DOM提供了接口来遍历树和提取相应的数据。
python还提供了python独特的xml解析方法,相比于SAX和DOM更容易使用和更加快速,此方法为ElementTree。
python的xml模块为:
1)xml.dom.minidom
2)xml.elementtree
3)xml.sax + xml.dom
二 xml实例:(employees.xml)



l inux
30


windows
20


三 使用xml.dom.minidom来读写xml
1)使用xml.dom.minidom来解析xml:
def TestMiniDom():
from xml.dom import minidom
doc = minidom.parse( "employees.xml" )
# get root element:
root = doc.documentElement
# get all children elements:
employees = root.getElementsByTagName( "employee" )
for employee in employees:
print ( " ------------------------------------------- " )
# element name : employee
print (employee.nodeName)
# element xml content : windows20
# basically equal to toprettyxml function
print (employee.toxml())
nameNode = employee.getElementsByTagName( "name" )[0]
print (nameNode.childNodes)
print (nameNode.nodeName + ":" + nameNode.childNodes[0].nodeValue)
ageNode = employee.getElementsByTagName( "age" )[0]
print (ageNode.childNodes)
print (ageNode.nodeName + ":" + ageNode.childNodes[0].nodeValue)
print ( " ------------------------------------------- " )
for n in employee.childNodes:
print (n)
TestMiniDom()
2)使用xml.dom.minidom来生成xml:
def CreateXml():
import xml.dom.minidom
impl = xml.dom.minidom.getDOMImplementation()
dom = impl.createDocument(None, 'employees' , None)
root = dom.documentElement
employee = dom.createElement( 'employee' )
root.appendChild(employee)
nameE = dom.createElement( 'name' )
nameT = dom.createTextNode( 'linux' )
nameE.appendChild(nameT)
employee.appendChild(nameE)
ageE = dom.createElement( 'age' )
ageT = dom.createTextNode( '30' )
ageE.appendChild(ageT)
employee.appendChild(ageE)
f = open( 'employees2.xml' , 'w')
dom.writexml(f, addindent = ' ' , newl = '\n' ,encoding = 'utf-8' )
f.close()
CreateXml()
3)使用xml.dom.minidom需要注意的
*使用parse()或createDocument()返回的为DOM对象;
*使用DOM的documentElement属性可以获得Root Element;
*DOM为树形结构,包含许多的nodes,其中element是node的一种,可以包含子elements,textNode也是node的一种,是最终的子节点;
*每个node都有nodeName,nodeValue,nodeType属性,nodeValue是结点的值,只对textNode有效。对于textNode,想得到它的文本内容可以使用: .data属性。
*nodeType是结点的类型,现在有以下:
'ATTRIBUTE_NODE''CDATA_SECTION_NODE''COMMENT_NODE''DOCUMENT_FRAGMENT_NODE'
'DOCUMENT_NODE''DOCUMENT_TYPE_NODE''ELEMENT_NODE''ENTITY_NODE''ENTITY_REFERENCE_NODE'
'NOTATION_NODE''PROCESSING_INSTRUCTION_NODE''TEXT_NODE'
*getElementsByTagName()可以根据名字来查找子elements;
*childNodes返回所有的子Nodes,其中所有的文本均为textNode,包含元素间的‘\n\r'和空格均为textNode;
*writexml() 时addindent=' '表示子元素的缩进,newl='\n'表示元素间的换行,encoding='utf-8'表示生成的xml的编码格式()。
希望本文所述对大家的Python程序设计有所帮助。

相关内容