赞
踩
XML(eXtensible Markup Language,可扩展标记语言):一种用于标记电子文件使其具有结构性的标记语言,被用来传输和存储数据
XML文档结构:一种树结构,从根部开始,扩展到枝叶
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
(1)根元素:XML 文档必须包含根元素,该元素是所有其他元素的父元素
(2)子元素:父元素拥有子元素,相同层级上的子元素成为同胞(兄弟或姐妹)
(3)类似HTML,所有的元素都可以有文本内容和属性
实例:在下图,根元素是bookstore,文档中所有的book元素都被包含在bookstore中,book元素有4个子元素:title, author, year, price
<bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore>
Python有三种方法解析XML:SAX, DOM, ElementTree
完整的SAX API文档:https://docs.python.org/3/library/xml.sax.html
SAX用事件驱动模型,通过解析XML的过程中触发一个个的事件,并调用用户定义的回调函数来处理XML文件。
(1)解析器:负责读取XML文档,并向事件处理器发送事件,如元素开始、元素结束事件
(2)事件处理器:负责对事件作出响应,对传递的XML数据进行处理。
通常应用于:①对大型文件进行处理;②只需要文件的部分内容,或者只需从文件中得到特定信息;③想建立自己的对象模型
在Python中使用SAX方式处理XML要先引入xml.sax中的parse函数,还有xml.sax.handler中的ContentHandler
xml.sax.make_parser([parser_list])
参数1 parser_list,可选参数,解析器列表
xml.sax.parse(xmlfile, contenthandler[, errorhandler])
参数1 xmlfile,xml文件名
参数2 contenthandler,必须是一个ContentHandler对象
参数3 errorhandler,如果指定该参数,errorhandler必须是一个SAX ErrorHandler对象
xml.sax.parseString(xmlstring, contenthandler[,errorhandler])
参数1 xmlstring,xml字符串
参数2 contenthandler,必须是一个ContentHandler对象
参数3 errorhandler,如果指定该参数,errorhandler必须是一个SAX ErrorHandler对象
characters(content)方法:调用时机:从行开始,遇到标签之前,存在字符,content的值为这些字符串。从一个标签,遇到下一个标签之前,存在字符,content的值为这些字符串;从一个标签,遇到行结束符之前,存在字符,content的值为这些字符串。标签可以是开始标签,也可以是结束标签。
startDocument()方法:文档启动的时候调用
endDocument()方法:解析器到达文档结尾时调用
startElement(name, attrs)方法:遇到XML开始标签时调用,name是标签的名字,attrs是标签的属性值字典
endElement(name)方法:遇到XML结束标签时调用
Python使用SAX解析XML实例:
movies.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>
import xml.sax class MovieHandler(xml.sax.ContentHandler): def __init__(self): self.CurrentData = "" self.type = "" self.format = "" self.year = "" self.rating = "" self.stars = "" self.description = "" # 元素开始调用 def startElement(self, tag, attributes): self.CurrentData = tag if tag == "movie": print ("*****Movie*****") title = attributes["title"] print ("Title:", title) # 元素结束调用 def endElement(self, tag): 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 = "" # 读取字符时调用 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 if ( __name__ == "__main__"): # 创建一个 XMLReader parser = xml.sax.make_parser() # 关闭命名空间 parser.setFeature(xml.sax.handler.feature_namespaces, 0) # 重写 ContextHandler Handler = MovieHandler() parser.setContentHandler( Handler ) parser.parse("movies.xml")
程序执行结果:
*****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Year: 2003 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
完整的DOM API文档:https://docs.python.org/3/library/xml.dom.html
DOM将XML数据在内存中解析成一个树,通过对树的操作来操作XML
利用DOM提供的不同函数读取或修改文档的内容和结构,也可以把修改的内容写入XML文件
Python使用xml.dom.minidom解析XML实例:
from xml.dom.minidom import parse import xml.dom.minidom # 使用minidom解析器打开XML文档 DOMTree = xml.dom.minidom.parse("movies.xml") collection = DOMTree.documentElement if collections.hasAttribute("shelf"): print("Root element: %s" % collection.getAttribute("shelf")) # 在集合中获取所有电影 movies = collection.getElementsByTagName("movie") # 打印每部电影的详细信息 for movie in movies: print ("*****Movie*****") if movie.hasAttribute("title"): print ("Title: %s" % movie.getAttribute("title")) type = movie.getElementsByTagName('type')[0] print ("Type: %s" % type.childNodes[0].data) format = movie.getElementsByTagName('format')[0] print ("Format: %s" % format.childNodes[0].data) rating = movie.getElementsByTagName('rating')[0] print ("Rating: %s" % rating.childNodes[0].data) description = movie.getElementsByTagName('description')[0] print ("Description: %s" % description.childNodes[0].data)
程序执行结果:
Root element : New Arrivals *****Movie***** Title: Enemy Behind Type: War, Thriller Format: DVD Rating: PG Description: Talk about a US-Japan war *****Movie***** Title: Transformers Type: Anime, Science Fiction Format: DVD Rating: R Description: A schientific fiction *****Movie***** Title: Trigun Type: Anime, Action Format: DVD Rating: PG Description: Vash the Stampede! *****Movie***** Title: Ishtar Type: Comedy Format: VHS Rating: PG Description: Viewable boredom
完整的ElementTree API文档:https://docs.python.org/3.6/library/xml.etree.elementtree.html
此部分详见:https://blog.csdn.net/weixin_36279318/article/details/79176475
xml.etree.ElementTree模块实现了一个简单而高效的API用于解析和创建XML数据,比DOM更加轻量化
import xml.etree.ElementTree as ET
tree = ET.parse('movies.xml')
root = tree.getroot()
>>> root.tag
'collection'
>>> root.attrib
{'shelf': 'New Arrivals'}
>>> for child in root:
... print(child.tag, child.attrib)
movie {'title': 'Enemy Behind'}
movie {'title': 'Transformers'}
movie {'title': 'Trigun'}
movie {'title': 'Ishtar'}
>>> root[0][1].text
'DVD'
Element.iter()
:递归地遍历它下面的所有子树
>>> for movie in root.iter('movie'):
... print(movie.attrib)
{'title': 'Enemy Behind'}
{'title': 'Transformers'}
{'title': 'Trigun'}
{'title': 'Ishtar'}
Element.findall()
:只找到带有标签的元素,该标签是当前元素的直接子元素
Element.find()
:找到第一个带有特定标签的子元素
Element.text
:访问标签的内容
Element.get()
:访问标签的属性值
>>> for movie in root.findall('movie'):
... type = movie.find('type').text
... name = movie.get('type')
... print(name, type)
None War, Thriller
None Anime, Science Fiction
None Anime, Action
None Comedy
ElementTree.write()
:创建xml或向xml写入数据
Element.set()
:添加和修改标签的属性和属性值
Element.append()
:添加孩子节点
Element.remove()
:删除满足条件的标签
SubElement()
:创建新的子元素
>>> a = ET.Element('a')
>>> b = ET.SubElement(a, 'b')
>>> c = ET.SubElement(a, 'c')
>>> d = ET.SubElement(c, 'd')
>>> ET.dump(a)
<a><b /><c><d /></c></a>
tree.write('test.xml',encoding='utf-8',xml_declaration=True) #设置xml_declaration为True即自动添加xml头部信息 <?xml version='1.0' encoding='utf-8'?>
def indent(elem, level = 0):
i = "\n" + level*"\t"
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + "\t"
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。