xml是一种便携式的开源语言,允许程序员开发可由其他应用程序读取的应用程序,而不管操作系统和/或开发语言是什么。
可扩展标记语言(xml)是一种非常像html或sgml的标记语言。 这是由万维网联盟推荐的,可以作为开放标准。
xml对于存储小到中等数量的数据非常有用,而不需要使用sql。
python标准库提供了一组极少使用但有用的接口来处理xml。两个最基本和最广泛使用在xml数据的api是sax和dom接口。
简单xml api(sax) - 在这里,注册感兴趣的事件回调,然后让解析器继续执行文档。 当文档较大或存在内存限制时,此功能非常有用,它会从文件读取文件时解析文件,并且整个文件不会存储在内存中。
文档对象模型(dom)api - 这是一个万维网联盟的推荐,它将整个文件读入存储器并以分层(基于树)的形式存储,以表示xml文档的所有功能。
当处理大文件时,sax显然无法与dom一样快地处理信息。 另一方面,使用dom专门可以真正地占用资源,特别是如果要加许多文件使用的时候。
sax是只读的,而dom允许更改xml文件。由于这两种不同的api相辅相成,在大型项目中一般根据需要使用它们。
对于我们所有的xml代码示例,使用一个简单的xml文件:movies.xml
作为输入 -
<collection shelf = "new arrivals">
<movie title = "enemy behind">
<type>war, thriller</type>
<format>dvd</format>
<year>2013</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>
sax是事件驱动的xml解析的标准接口。 使用sax解析xml通常需要通过子类化xml.sax.contenthandler
来创建自己的contenthandler
。contenthandler
处理xml样式/风格的特定标签和属性。 contenthandler
对象提供了处理各种解析事件的方法。它拥有的解析器在解析xml文件时调用contenthandler
方法。
在xml文件的开头和结尾分别调用:startdocument
和enddocument
方法。 characters(text)
方法通过参数text
传递xml文件的字符数据。
contenthandler
在每个元素的开头和结尾被调用。如果解析器不在命名空间模式下,则调用startelement(tag,attributes)
和endelement(tag)
方法; 否则,调用相应的方法startelementns
和endelementns
方法。 这里,tag
是元素标签,属性是attributes
对象。
以下是继续前面了解的其他重要方法 -
make_parser()方法
以下方法创建一个新的解析器对象并返回它。创建的解析器对象将是系统查找的第一个解析器类型。
xml.sax.make_parser( [parser_list] )
以下是参数的详细信息 -
make_parser
方法。parse()方法
以下方法创建一个sax解析器并使用它来解析文档。
xml.sax.parse( xmlfile, contenthandler[, errorhandler])
以下是参数的详细信息 -
contenthandler
对象。errorhandler
必须是sax errorhandlerparsestring方法
还有一种方法来创建sax解析器并解析指定的xml字符串。
xml.sax.parsestring(xmlstring, contenthandler[, errorhandler])
以下是参数的详细信息 -
contenthandler
对象。errorhandler
必须是sax errorhandler
对象。示例
#!/usr/bin/python3
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 = ""
# call when an element starts
def startelement(self, tag, attributes):
self.currentdata = tag
if tag == "movie":
print ("*****movie*****")
title = attributes["title"]
print ("title:", title)
# call when an elements ends
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 = ""
# call when a character is read
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__"):
# create an xmlreader
parser = xml.sax.make_parser()
# turn off namepsaces
parser.setfeature(xml.sax.handler.feature_namespaces, 0)
# override the default 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
有关sax api文档的完整详细信息,请参阅标准python sax api。
文档对象模型(“dom”)是来自万维网联盟(w3c)的跨语言api,用于访问和修改xml文档。
dom对于随机访问应用非常有用。sax只允许您一次查看文档的一部分。如果想要查看一个sax元素,则无法访问另一个。
以下是快速加载xml文档并使用xml.dom
模块创建minidom对象的最简单方法。 minidom对象提供了一个简单的解析器方法,可以从xml文件快速创建一个dom树。
示例调用minidom
对象的parse(file [,parser])
函数来解析由文件指定为dom树对象的xml文件。
示例
#!/usr/bin/python3
from xml.dom.minidom import parse
import xml.dom.minidom
# open xml document using minidom parser
domtree = xml.dom.minidom.parse("movies.xml")
collection = domtree.documentelement
if collection.hasattribute("shelf"):
print ("root element : %s" % collection.getattribute("shelf"))
# get all the movies in the collection
movies = collection.getelementsbytagname("movie")
# print detail of each 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
有关dom api文档的完整详细信息,请参阅标准python dom api。