python网络编程学习笔记(八):XML生成与解析(DOM、ElementTree)
xml.dom篇
DOM是DocumentObjectModel的简称,XML文档的高级树型表示。该模型并非只针对Python,而是一种普通XML模型。Python的DOM包是基于SAX构建的,并且包括在Python2.0的标准XML支持里。
一、xml.dom的简单介绍
1、主要方法:
minidom.parse(filename):加载读取XML文件
doc.documentElement:获取XML文档对象
node.getAttribute(AttributeName):获取XML节点属性值
node.getElementsByTagName(TagName):获取XML节点对象集合
node.childNodes:返回子节点列表。
node.childNodes[index].nodeValue:获取XML节点值
node.firstChild:访问第一个节点,等价于pagexml.childNodes[0]
返回Node节点的xml表示的文本:
doc=minidom.parse(filename)
doc.toxml('UTF-8')
访问元素属性:
Node.attributes["id"]
a.name#就是上面的"id"
a.value#属性的值
2、举例说明
例1:文件名:book.xml
<?xmlversion="1.0"encoding="utf-8"?> <info> <intro>Bookmessage</intro> <listid='001'> <head>bookone</head> <name>pythoncheck</name> <number>001</number> <page>200</page> </list>
<listid='002'> <head>booktwo</head> <name>pythonlearn</name> <number>002</number> <page>300</page> </list>
</info>