什么是XML?
XML指可扩展标记语言(eXtensible Markup Language);
特点:
1. XML与操作系统, 编程语言的开发平台无关
2. 实现不同系统之间的数据交换
作用:
1. 数据交换
2. 配置应用程序和网站
3. 节点自由扩展
Python有三种方法解析XML : SAX,DOM,以及ElementTree
1.SAX (simple API for XML )
pyhton 标准库包含SAX解析器,SAX用事件驱动模型,通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。
2.DOM(Document Object Model)
将XML数据在内存中解析成一个树,通过对树的操作来操作XML。因DOM需要将XML数据映射到内存中的树,一是比较慢,二是比较耗内存,而SAX流式读取XML文件,比较快,占用内存少,但需要用户实现回调函数(handler)。
3.ElementTree(元素树)
ElementTree就像一个轻量级的DOM,具有方便友好的API。代码可用性好,速度快,消耗内存少。
注:
< movie name = 'CCTV'> hello,world</movie>
tag,即标签,用于标识该元素表示哪种数据,即 movie
一 . 使用 SAX 解析 xml
1 . 准备一份XML格式的文件
选择创建类型: 定义文件名字
<collection shelf="New Arrivals">
<movie title="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title="Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
2.需要知道所用到的命令:
a. ContentHandler类方法介绍
characters(content)方法
调用时机:
从行开始,遇到标签之前,存在字符,content的值为这些字符串。
从一个标签,遇到下一个标签之前, 存在字符,content的值为这些字符串。
从一个标签,遇到行结束符之前,存在字符,content的值为这些字符串。
标签可以是开始标签,也可以是结束标签。
startElement(name, attrs) 方法
遇到XML开始标签时调用,name是标签的名字,attrs是标签的属性值字典。
endElement(name) 方法
遇到XML结束标签时调用。
b. make_parser () 方法
xml.sax.make_parser( [parser_list] ) 创建一个新的解析器对象并返回
参数说明: parser_list - 可选参数,解析器列表
c. parser () 方法
xml.sax.parse( xmlfile, contenthandler[, errorhandler]) 创建一个 SAX 解析器并解析xml文档
参数说明:
xmlfile - xml文件名
contenthandler - 必须是一个ContentHandler的对象
errorhandler - 如果指定该参数,errorhandler必须是一个SAX ErrorHandler对象
开始进行操作:
import xml.sax #引入模块
#创建类方法 ContentHandler
class MoveHandler(xml.sax.ContentHandler):
def __init__(self):
self.CurrentData=''
self.type=''
self.format=''
self.year=''
self.rating=''
self.stars=''
self.description=''
# 元素开始调用
def startElement(self, tag, attrs):
self.CurrentData=tag
if tag=='movie':
print('***movie***')
title = attrs["title"]
print("Title:", title)
#读取字符时调用
def characters(self, content):
if self.CurrentData=='type':
self.type=content
elif self.CurrentData=='format':
self.format=content
elif self.CurrentData=='year':
self.year=content
elif self.CurrentData=='rating':
self.rating=content
elif self.CurrentData=='stars':
self.stars=content
elif self.CurrentData=='description':
self.description=content
# 元素结束调用
def endElement(self, name):
if self.CurrentData=='type':
print('type: ',self.type)
elif self.CurrentData=='format':
print('format: ',self.format)
elif self.CurrentData=='year':
print('year: ',self.year)
elif self.CurrentData=='rating':
print('rating: ',self.rating)
elif self.CurrentData=='stars':
print('stars: ',self.stars)
elif self.CurrentData=='description':
print('description: ',self.description)
#清空, 缓冲区
self.CurrentData=''
if __name__=='__main__':
# 创建一个 新的 XMLReader(xml解析) 对象
parser = xml.sax.make_parser()
# 关闭命名空间
parser.setFeature(xml.sax.handler.feature_namespaces,0)
# 重写 ContextHandler
Hadler= MoveHandler()
parser.setContentHandler(Hadler)
parser.parse('电影.xml')
输出为:
***movie***
Title: Enemy Behind
type: War, Thriller
format: DVD
year: 2013
rating: PG
stars: 10
description: Talk about a US-Japan war
***movie***
Title: Transformers
type: Anime, Science Fiction
format: DVD
year: 1989
rating: R
stars: 8
description: A schientific fiction
***movie***
Title: Trigun
type: Anime, Action
format: DVD
rating: PG
stars: 10
description: Vash the Stampede!
***movie***
Title: Ishtar
type: Comedy
format: VHS
rating: PG
stars: 2
description: Viewable boredom
二 . ElementTree解析XML文件
首先创建一个XML文件
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
进行代码处理:
import xml.etree.ElementTree as ET #引入模块 并重新命名
#先加载文档到内存里 形成一个倒桩的树
tree=ET.parse('newXML.xml')
#获取根节点
root=tree.getroot()
print('tag: ',root.tag,'attrib: ',root.attrib,'text: ',root.text)
#用遍历的方法进行抓取(粗糙):
for ele in root:
print('ele-tag: ', ele.tag, 'attrib: ', ele.attrib)
for e in ele:
print('e-tag: ', e.tag, 'attrib: ',e.attrib, 'text: ', e.text)
输出为:
tag: data attrib: {} text:
ele-tag: country attrib: {'name': 'Liechtenstein'}
e-tag: rank attrib: {} text: 1
e-tag: year attrib: {} text: 2008
e-tag: gdppc attrib: {} text: 141100
e-tag: neighbor attrib: {'name': 'Austria', 'direction': 'E'} text: None
e-tag: neighbor attrib: {'name': 'Switzerland', 'direction': 'W'} text: None
ele-tag: country attrib: {'name': 'Singapore'}
e-tag: rank attrib: {} text: 4
e-tag: year attrib: {} text: 2011
e-tag: gdppc attrib: {} text: 59900
e-tag: neighbor attrib: {'direction': 'N', 'name': 'Malaysia'} text: None
ele-tag: country attrib: {'name': 'Panama'}
e-tag: rank attrib: {} text: 68
e-tag: year attrib: {} text: 2011
e-tag: gdppc attrib: {} text: 13600
e-tag: neighbor attrib: {'direction': 'W', 'name': 'Costa Rica'} text: None
e-tag: neighbor attrib: {'direction': 'E', 'name': 'Colombia'} text: None
tag: data attrib: {} text:
另一种办法, (殊途同归) 进行优化处理:
import xml.etree.ElementTree as ET #引入模块 并重新命名
#先加载文档到内存里 形成一个倒桩的树
tree=ET.parse('newXML.xml')
#获取根节点
root=tree.getroot()
#用字典的方式 , 进行处理
dic={} #创建一个字典
for ele in root:
value=[]
for e in ele:
if e.text is None:
value.append(e.attrib)
else:
value.append({e.tag:e.text})
dic[ele.attrib['name']]=value
print(dic)
{'Liechtenstein': [{'rank': '1'}, {'year': '2008'}, {'gdppc': '141100'},
{'name': 'Austria', 'direction': 'E'}, {'name': 'Switzerland', 'direction': 'W'}],
'Singapore': [{'rank': '4'}, {'year': '2011'}, {'gdppc': '59900'},
{'direction': 'N', 'name': 'Malaysia'}],
'Panama': [{'rank': '68'}, {'year': '2011'}, {'gdppc': '13600'},
{'direction': 'W', 'name': 'Costa Rica'}, {'direction': 'E', 'name': 'Colombia'}]}
查找指定的子节点:
find('nodeName'):表示在该节点下,查找其中第一个tag为nodeName的节点。
findall('nodeName'):表示在该节点下,查找其中所有tag为nodeName的节点。
import xml.etree.ElementTree as ET #引入模块 并重新命名
tree=ET.parse('newXML.xml')
root=tree.getroot()
#查找指定的子节点:
node=root.find('country')
print(node.attrib['name'])
#输出为: Liechtenstein
nodes=root.findall('country')
for i in nodes:
print(i)
'''
<Element 'country' at 0x0309D750>
<Element 'country' at 0x0309D930>
<Element 'country' at 0x0309DA80>
'''
删除指定的节点以及保存
import xml.etree.ElementTree as ET #引入模块 并重新命名
tree=ET.parse('newXML.xml')
root=tree.getroot()
nodes=root.findall('country')
for node in nodes:
if node.attrib['name']=='Liechtenstein':
root.remove(node)
break
tree.write('newXML.xml') #重新写入 不可乎略的一步
print('完成')
最终结果:
<?xml version="1.0"?>
<data>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>