python网络编程学习笔记(8):XML生成与解析(DOM、ElementTree)
<div id="cnblogs_post_body">转载请注明:@小五义http://www.cnblogs.com/xiaowuyixml.dom篇
DOM是Document Object Model的简称,XML 文档的高级树型表示。该模型并非只针对 Python,而是一种普通XML 模型。Python 的 DOM 包是基于 SAX 构建的,并且包括在 Python 2.0 的标准 XML 支持里。
一、xml.dom的简单介绍
1、主要方法:
minidom.parse(filename):加载读取XML文件
doc.documentElement:获取XML文档对象
node.getAttribute(AttributeName):获取XML节点属性值
node.getElementsByTagName(TagName):获取XML节点对象集合
node.childNodes :返回子节点列表。
node.childNodes.nodeValue:获取XML节点值
node.firstChild:访问第一个节点,等价于pagexml.childNodes
返回Node节点的xml表示的文本:
doc = minidom.parse(filename)
doc.toxml('UTF-8')
访问元素属性:
Node.attributes["id"]
a.name #就是上面的 "id"
a.value #属性的值
2、举例说明
例1:文件名:book.xml
<div class="cnblogs_code" style="background-color: #f5f5f5; border: #cccccc 1px solid; padding: 5px;"><?xml version="1.0" encoding="utf-8"?><info> <intro>Book message</intro> <list id='001'> <head>bookone</head> <name>python check</name> <number>001</number> <page>200</page> </list> <list id='002'> <head>booktwo</head> <name>python learn</name> <number>002</number> <page>300</page> </list></info>
页:
[1]