做app 的模板下载网站有哪些,建设工程施工合同最新版本,wordpress可视化编辑插件,厦门网站建设 金猪1、Python 对 XML 的解析
1.1 SAX (simple API for XML )
SAX 解析器使用事件驱动模型#xff0c;通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。
xml.sax 模块牺牲了便捷性来换取速度和内存占用。
事件驱动指一种基于回调#xff08;ca…1、Python 对 XML 的解析
1.1 SAX (simple API for XML )
SAX 解析器使用事件驱动模型通过在解析XML的过程中触发一个个的事件并调用用户定义的回调函数来处理XML文件。
xml.sax 模块牺牲了便捷性来换取速度和内存占用。
事件驱动指一种基于回调callback机制的程序运行方法。
利用SAX解析XML文档牵涉到两个部分:
解析器负责读取XML文档并向事件处理器发送事件如元素开始跟元素结束事件。事件处理器负责对事件作出响应对传递的XML数据进行处理。
SAX适用场景
对大型文件进行处理只需要文件的部分内容或者只需从文件中得到特定信息。想建立自己的对象模型的时候。
1.2 DOM(Document Object Model)
DOM 解析器在任何处理开始之前必须把基于XML文件生成的树状数据放在内存所以DOM解析器的内存使用量完全根据输入资料的大小。
xml.dom.minidom minidom 是DOM API的极简化实现比完整版的DOM要简单的多而且这个包也小的多。xml.dom.pulldom pulldom模块提供的是一个“pull解析器”其背后的基本概念指的是从XML流中pull事件然后进行处理。虽然与SAX一样采用事件驱动模型event-driven processing model但是不同的是使用pull解析器时使用者需要明确地从XML流中pull事件并对这些事件遍历处理直到处理完成或者出现错误。
1.3 ElementTree(元素树)
xml.etree.ElementTree 模块提供了一个轻量级、Pythonic的API同时还有一个高效的C语言实现即 xml.etree.cElementTree 。
与 DOM 相比ET的速度更快API使用更直接、方便。 与 SAX 相比ET.iterparse 函数同样提供了按需解析的功能不会一次性在内存中读入整个文档。ET的性能与SAX模块大致相仿但是它的API更加高层次用户使用起来更加便捷。
1.4 xml.parser.expat
xml.parser.expat 提供了对C语言编写的expat解析器的一个直接的、底层API接口。expat接口与SAX类似也是基于事件回调机制但是这个接口并不是标准化的只适用于expat库。
expat是一个面向流的解析器。您注册的解析器回调或handler功能然后开始搜索它的文档。当解析器识别该文件的指定的位置它会调用该部分相应的处理程序如果您已经注册的一个。该文件被输送到解析器会被分割成多个片断并分段装到内存中。因此expat可以解析那些巨大的文件。
1.5 lxml
lxml 是一个第三方库它提供了更强大的XML处理功能包括XPath支持、XML Schema验证、HTML支持等。
1.6 xmltodict
xmltodict是一个第三方库它提供了一个功能将Python的字典对象转换为XML反之亦然。
2、示例
XML 实例文件 movies.xml 内容如下
collection shelfNew Arrivals
movie titleEnemy BehindtypeWar, Thriller/typeformatDVD/formatyear2003/yearratingPG/ratingstars10/starsdescriptionTalk about a US-Japan war/description
/movie
movie titleTransformerstypeAnime, Science Fiction/typeformatDVD/formatyear1989/yearratingR/ratingstars8/starsdescriptionA schientific fiction/description
/moviemovie titleTriguntypeAnime, Action/typeformatDVD/formatepisodes4/episodesratingPG/ratingstars10/starsdescriptionVash the Stampede!/description
/movie
movie titleIshtartypeComedy/typeformatVHS/formatratingPG/ratingstars2/starsdescriptionViewable boredom/description
/movie
/collection2.1 xml.sax
#!/usr/bin/python
# -*- coding: UTF-8 -*-import xml.saxclass 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 tagif tag movie:print *****Movie*****title attributes[title]print Title:, title# 元素结束事件处理def endElement(self, tag):if self.CurrentData type:print Type:, self.typeelif self.CurrentData format:print Format:, self.formatelif self.CurrentData year:print Year:, self.yearelif self.CurrentData rating:print Rating:, self.ratingelif self.CurrentData stars:print Stars:, self.starselif self.CurrentData description:print Description:, self.descriptionself.CurrentData # 内容事件处理def characters(self, content):if self.CurrentData type:self.type contentelif self.CurrentData format:self.format contentelif self.CurrentData year:self.year contentelif self.CurrentData rating:self.rating contentelif self.CurrentData stars:self.stars contentelif self.CurrentData description:self.description contentif ( __name__ __main__):# 创建一个 XMLReaderparser xml.sax.make_parser()# turn off namepsacesparser.setFeature(xml.sax.handler.feature_namespaces, 0)# 重写 ContextHandlerHandler 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 boredom2.2 xml.dom
#!/usr/bin/python
# -*- coding: UTF-8 -*-from xml.dom.minidom import parse
import xml.dom.minidom# 使用minidom解析器打开 XML 文档
DOMTree xml.dom.minidom.parse(movies.xml)
collection DOMTree.documentElement
if collection.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].dataformat movie.getElementsByTagName(format)[0]print Format: %s % format.childNodes[0].datarating movie.getElementsByTagName(rating)[0]print Rating: %s % rating.childNodes[0].datadescription 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 boredom2.3 xml.etree.ElementTree
import xml.etree.ElementTree as ETxml_string book id10086title langenGood Omens/titleauthorsnameNeil Gaiman/namenameTerry Pratchett/name/authorsyear1990/year/bookroot ET.fromstring(xml_string)# 获取根元素的标签
print(root.tag)# 获取根元素的文本内容
print(root.text)# 获取根元素的属性
print(root.attrib)# 查找第一个title元素
print(root.find(title).text)# 查找所有author元素
names root.find(authors).findall(name)
for name in names:print(name.text)# 修改title元素的文本内容
root.find(title).text The Nice and Accurate Prophecies of Agnes Nutter, Witch# 添加一个新的元素
new_year ET.SubElement(root, year)
new_year.text 2024# 将修改后的元素转换为字符串
new_xml_string ET.tostring(root, encodingunicode)
print(new_xml_string)运行结果
book{id: 10086}
Good Omens
Neil Gaiman
Terry Pratchett
book id10086title langenThe Nice and Accurate Prophecies of Agnes Nutter, Witch/titleauthorsnameNeil Gaiman/namenameTerry Pratchett/name/authorsyear1990/yearyear2024/year/book 10、资料
Python xmlPython 解析 XML 数据Python xml 解析Python SAX