xml 解析 python

1 综述

有很多种解析方法

(1) DOM 缺点是:1 不能解析格式不正确或者不规则xml 2据说只能解析utf-8格式,非utf-8需要转码

与SAX比较,DOM典型的缺点是比较慢,消耗更多的内存,因为DOM会将整个XML数读入内存中,并为树
中的第一个节点建立一个对象。使用DOM的好处是你不需要对状态进行追踪,因为每一个节点都知道谁是它的
父节点,谁是子节点。但是DOM用起来有些麻烦。


Python中使用minidom解析xml,会遇到编码问题。minidom支持UTF-8的编码,对于其他的编码,必须进行转换,否则解析时会产生异常。下面以读取gb2312编码的xml文件为例。

sourceFile = codecs.open(sourceFilePath,mode='r')

xmlContentStr = sourceFile.read()

xmlContentStr = xmlContentStr.decode('gb2312').encode('utf-8')

xmlContentStr =xmlContentStr.replace('encoding="gb2312"','encoding="utf-8"')

sourceXML = minidom.parseString(xmlContentStr)



(2)beatifulsoup 特点是可以处理格式不正确的html文档

(3).SAX (simple API for XML )
pyhton 标准库包含SAX解析器,SAX是一种典型的极为快速的工具,在解析XML时,不会占用大量内存。

但是这是基于回调机制的,因此在某些数据中,它会调用某些方法进行传递。这意味着必须为数据指定句柄,
以维持自己的状态,这是非常困难的。

(4) ElementTree(元素树)
ElementTree就像一个轻量级的DOM,具有方便友好的API。代码可用性好,速度快,消耗内存少,这里主要
介绍ElementTree。


2DOM(Document Object Model)

与SAX比较,DOM典型的缺点是比较慢,消耗更多的内存,因为DOM会将整个XML数读入内存中,并为树
父节点,谁是子节点。但是DOM用起来有些麻烦。

一 、xml.dom 解析XML的API描述


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]

doc = minidom.parse(filename)
doc.toxml('UTF-8')
返回Node节点的xml表示的文本


Node.attributes["id"]
a.name #就是上面的 "id"
a.value #属性的值
访问元素属性

二、代码演示

1、创建user.xml文件添加XMl节点

<?xml version="1.0" encoding="UTF-8" ?>
<users>
user id="1000001">
username>Admin</email>admin@live.cnage>23sex>user="1000002">Admin2>admin2@live.cn>22="1000003">Admin3>admin3@live.cn>27="1000004">Admin4>admin4@live.cn>25>="1000005">Admin5>admin5@live.cn>20="1000006">Admin6>admin6@live.cn>
>

2、Demo.py解析user.xml文档数据

# -*- coding:utf-8 -*-
"""
* User: lhj588
* Date: 11-11-9
* Time: 13:20
* Desc:
"""
from xml.dom import minidom


def get_attrvalue(node,attrname):
return node.getAttribute(attrname) if node else ''

def get_nodevalue(node,index = 0):
return node.childNodes[index].nodeValue def get_xmlnode(node,name):
return node.getElementsByTagName(name) else []

def xml_to_string(filename='user.xml'):
doc = minidom.parse(filename)
return doc.toxml(UTF-8')

def get_xml_data(filename='):
doc = minidom.parse(filename)
root = doc.documentElement

user_nodes = get_xmlnode(root,user')
user_list=[]
for node in user_nodes:
user_id = get_attrvalue(node,0); line-height:1.5!important">id')
node_name = get_xmlnode(node,0); line-height:1.5!important">username')
node_email = get_xmlnode(node,0); line-height:1.5!important">email')
node_age = get_xmlnode(node,0); line-height:1.5!important">age')
node_sex = get_xmlnode(node,0); line-height:1.5!important">sex')

user_name =get_nodevalue(node_name[0]).encode(utf-8',0); line-height:1.5!important">ignore')
user_email = get_nodevalue(node_email[0]).encode(')
user_age = int(get_nodevalue(node_age[0]))
user_sex = get_nodevalue(node_sex[0]).encode(')
user = {}
user['],user['] = (
int(user_id),user_name,user_email,user_age,user_sex
)
user_list.append(user)
return user_list

def test_xmltostring():
print xml_to_string()

def test_laod_xml():
user_list = get_xml_data()
for user in user_list :
print user['sex']
print -----------------------------------------------------'
if user:
user_str=编 号:%d\n用户名%s\n性 别:%s\n年 龄:%s\n邮 箱:%s\n ' % (int(user[']),0); line-height:1.5!important">'])
print user_str
====================================================='

if __name__ == "__main__":
test_xmltostring()
test_laod_xml()


3、测试效果

A、测试toxml

demo.py 文件修改
if __name__ == "__main__":
test_xmltostring()
 执行打印结果:
>
B、测试解析XML
demo.py 文件修改

if __name__ == "__main__":
test_laod_xml()

执行打印出结果:
-----------------------------------------------------
编 号:1000001
用户名:Admin
性 别:男
年 龄:23
邮 箱:admin@live.cn

=====================================================
-----------------------------------------------------
编 号:1000002
用户名:Admin2
性 别:男
年 龄:22
邮 箱:admin2@live.cn

=====================================================
-----------------------------------------------------
编 号:1000003
用户名:Admin3
性 别:男
年 龄:27
邮 箱:admin3@live.cn

=====================================================
-----------------------------------------------------
编 号:1000004
用户名:Admin4
性 别:女
年 龄:25
邮 箱:admin4@live.cn

=====================================================
-----------------------------------------------------
编 号:1000005
用户名:Admin5
性 别:男
年 龄:20
邮 箱:admin5@live.cn

=====================================================
-----------------------------------------------------
编 号:1000006
用户名:Admin6
性 别:女
年 龄:23
邮 箱:admin6@live.cn

=====================================================

转自:http://www.cnblogs.com/lhj588/archive/2011/11/09/2242483.html

3 Beautiful Soup

Beautiful Soup 是用 Python 写的一个 HTML/XML 的解析器,它可以很好的处理不规范标记生成剖析树。通常用来分析爬虫抓取的web文档。对于 不规则的 Html文档,也有很多的补全功能,节省了开发者的时间和精力。

Beautiful Soup 的官方文档齐全,将官方给出的例子实践一遍就能掌握。官方英文文档中文文档

一 安装Beautiful Soup

安装 BeautifulSoup 很简单,下载BeautifulSoup源码。解压运行

python setup.py install 即可。

测试安装是否成功。键入 import BeautifulSoup 如果没有异常,即成功安装

二 使用 BeautifulSoup

1. 导入BeautifulSoup ,创建BeautifulSoup 对象

1
2
3
4
5
6
7
8
9
10
11
12
from BeautifulSoup import BeautifulSoup # HTML
BeautifulStonesoup # XML
# ALL
doc = [
'<html><head><title>Page title</title></head>' ,
'<body><p id="firstpara" align="center">This is paragraph <b>one</b>.' ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
'<p id="secondpara" align="blah">This is paragraph <b>two</b>.' ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
'</html>'
]
# BeautifulSoup 接受一个字符串参数
soup BeautifulSoup(''.join(doc))

2. BeautifulSoup对象简介

用BeautifulSoup 解析 html文档时,BeautifulSoup将 html文档类似 dom文档树一样处理。BeautifulSoup文档树有三种基本对象。

2.1. soup BeautifulSoup.BeautifulSoup

1
2
type (soup)
< class 'BeautifulSoup.BeautifulSoup' >

2.2. 标记 BeautifulSoup.Tag

(soup.html)
'BeautifulSoup.Tag' 2.3 文本 BeautifulSoup.NavigableString

(soup.title.string)
'BeautifulSoup.NavigableString' 3. BeautifulSoup 剖析树

3.1BeautifulSoup.Tag对象方法

获取 标记对象(Tag)

标记获取法 ,直接用 soup对象加标记名,返回 tag对象.这种方式,选取唯一标签的时候比较有用。或者根据树的结构去选取,一层层的选择

1
2
3
4
5
6
7
>>> html = soup.html
>>> html
< html >< head title >Page title</ ></ body p id = "firstpara" align "center" >This is paragraph< b >one</ >.</ p "secondpara" "blah" >two</ >
>>> type(html)
class 'BeautifulSoup.Tag'>
>>> title = soup.title
content方法

content方法 根据文档树进行搜索,返回标记对象(tag)的列表

1
2
>>> soup.contents
[<html><head><title>Page title< / title>< head><body><p id = "firstpara" align "center" >This is paragraph<b>one< b>.< p><p "secondpara" "blah" paragraph<b>two< p>< body>< html>]
1
2
3
4
5
6
>>> soup.contents[ 0 ].contents
[<head><title>Page title< head>,<body><p body>]
>>> len (soup.contents[ ].contents)
2
].contents[ 1 ])
使用contents向后遍历树,使用parent向前遍历树

next 方法

获取树的子代元素,包括Tag对象 和NavigableString对象。。。

1
2
3
4
>>> head. next
<title>Page title< title>
next . next
u 'Page title'
1
2
3
4
5
>>> p1 soup.p
>>> p1
<p p>
>>> p1. next
'This is paragraph'

nextSibling 下一个兄弟对象包括Tag对象 和NavigableString对象

1
2
3
4
>>> head.nextSibling
<body><p body>
.nextSibling
<b>one< b>

nextSibling 相似的是prevIoUsSibling,即上一个兄弟节点。

replacewith方法

将对象替换为,接受字符串参数

1
2
3
4
5
6
7
8
9
10
11
12
>>> head soup.head
>>> head
<head><title>Page title< head>
>>> head.parent
<html><head><title>Page title< html>
>>> head.replaceWith( 'head was replace' )
>>> head
head>
>>> head.parent
>>> soup
<html>head was replace<body><p html>
>>>

搜索方法

搜索提供了两个方法一个是 find,一个是findAll。这里的两个方法(findAll和 find)仅对Tag对象以及,顶层剖析对象有效,但 NavigableString不可用。

findAll(name,attrs,recursive,text,limit,**kwargs)

接受一个参数,标记

寻找文档所有 P标记,返回一个列表

1
2
3
4
>>> soup.findAll( 'p' )
[<p p>,<p p>]
(soup.findAll( ))
< type 'list' 寻找 id="secondpara"的 p 标记,返回一个结果集

1
2
3
>>> pid = ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas, 'firstpara' ))
>>> pid
'BeautifulSoup.ResultSet' 一个属性或多个属性

>>> p2 soup.findAll(ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.1em!important; outline:0px!important; overflow:visible!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,{'align':'blah'})
>>> p2
p>]
(p2)
利用正则表达式

1
2
>>> soup.findAll( re. compile ( "para$" p>]

读取和修改属性

>>> p1['id']
'firstpara'
] 'changeid'
>>> p1
"changeid" p>
'class' 'new class'
>>> p1
"center" class "new class" p>
剖析树基本方法就这些,还有其他一些,以及如何配合正则表达式。具体请看官方文档

3.2BeautifulSoup.NavigableString对象方法

NavigableString对象方法比较简单,获取内容

1
2
3
4
5
6
7
8
9
>>> soup.title
>>> title soup.title. >>> title
'Page title'
(title)
>
>>> title.string
'Page title'

至于如何遍历树,进而分析文档,已经 XML 文档的分析方法,可以参考官方文档。


转自:http://rsj217.diandian.com/post/2012-11-01/40041235132

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念