环境

python:3.4.4

准备xml文件

首先新建一个xml文件,countries.xml。内容是在python官网上看到的。

<?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>

准备python文件

新建一个test_SAX.py,用来解析xml文件。

#!/usr/bin/python
# -*- coding: UTF-8 -*- import xml.sax class CountryHandler( xml.sax.ContentHandler ):
def __init__(self):
self.CurrentData = ""
self.CurrentAttributes = ""
self.rank = ""
self.year = ""
self.gdppc = ""
self.nei_name = ""
self.nei_dire = "" def startElement(self, tag, attributes):
self.CurrentData = tag
self.CurrentAttributes = attributes
if tag == "country":
print ("*****Country*****")
name = attributes["name"]
print ("Name:", name)
if tag == "neighbor":
self.nei_name = attributes["name"]
self.nei_dire = attributes["direction"] def endElement(self, tag):
if self.CurrentData == "rank":
print ("Rank:", self.rank)
elif self.CurrentData == "year":
print ("Year:", self.year)
elif self.CurrentData == "gdppc":
print ("Gdppc:", self.gdppc)
elif self.CurrentData == "neighbor":
print ("Neighbor:", self.nei_name,self.nei_dire)
self.CurrentData = ""
self.nei_name = ""
self.nei_dire = "" def characters(self, content):
if self.CurrentData == "rank":
self.rank = content
elif self.CurrentData == "year":
self.year = content
elif self.CurrentData == "gdppc":
self.gdppc = content if __name__ == "__main__":
parser = xml.sax.make_parser()
parser.setFeature(xml.sax.handler.feature_namespaces, 0)
Handler = CountryHandler()
parser.setContentHandler( Handler )
parser.parse("countries.xml")

执行结果

>python test_SAX.py
*****Country*****
Name: Liechtenstein
Rank: 1
Year: 2008
Gdppc: 141100
Neighbor: Austria E
Neighbor: Switzerland W
*****Country*****
Name: Singapore
Rank: 4
Year: 2011
Gdppc: 59900
Neighbor: Malaysia N
*****Country*****
Name: Panama
Rank: 68
Year: 2011
Gdppc: 13600
Neighbor: Costa Rica W
Neighbor: Colombia E

备注

SAX是一种基于事件驱动的API。

SAX主要包括三种对象: readers,handlers 以及 input sources。即解析器,事件处理器以及输入源。

解析器负责读取输入源,如xml文档,并向事件处理器发送事件,如元素开始和元素结束事件。

事件处理器负责处理事件,对xml文档数据进行处理。

parser = xml.sax.make_parser()

新建并且返回一个 SAX XMLReader 对象。

参见: https://docs.python.org/2/library/xml.sax.html

xml.sax.make_parser([parser_list])
Create and return a SAX XMLReader object. The first parser found will be used. If parser_list is provided, it must be a sequence of strings which name modules that have a function named create_parser(). Modules listed in parser_list will be used before modules in the default list of parsers.

parser.setFeature(xml.sax.handler.feature_namespaces, 0)

设置xml.sax.handler.feature_namespaces值为0。其实就是关闭 namespace模式。

参见:https://docs.python.org/2/library/xml.sax.reader.html

XMLReader.setFeature(featurename, value)
Set the featurename to value. If the feature is not recognized, SAXNotRecognizedException is raised. If the feature or its setting is not supported by the parser, SAXNotSupportedException is raised.

class CountryHandler( xml.sax.ContentHandler )

SAX API 定义了4种handler:content handler,DTD handler,error handlers,和 entity resolvers。

程序只需要实现自己感兴趣的事件的接口,比如我们这里只实现了 ContentHandler接口里的部分方法。

class xml.sax.handler.ContentHandler
This is the main callback interface in SAX, and the one most important to applications. The order of events in this interface mirrors the order of the information in the document.

ContentHandler 有很多方法。具体可参见: https://docs.python.org/2/library/xml.sax.handler.html#contenthandler-objects

我们这里首先新建一个CountryHandler类,继承自 xml.sax.ContentHandler。然后实现了他的 startElement(),endElement() 以及 characters()方法。

def startElement(self, tag, attributes)

遇到XML开始标签时调用。tag是标签的名字,attributes 是标签的属性值字典。

Signals the start of an element in non-namespace mode.

The name parameter contains the raw XML 1.0 name of the element type as a string and the attrs parameter holds an object of the Attributes interface (see The Attributes Interface) containing the attributes of the element. The object passed as attrs may be re-used by the parser; holding on to a reference to it is not a reliable way to keep a copy of the attributes. To keep a copy of the attributes, use the copy() method of the attrs object.

def endElement(self, tag)

遇到XML结束标签时调用。tag是标签的名字。

Signals the end of an element in non-namespace mode.
The name parameter contains the name of the element type, just as with the startElement() event.

def characters(self, content)

遇到XML元素内容时调用。content为元素的内容值。

Receive notification of character data.

The Parser will call this method to report each chunk of character data. SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks; however, all of the characters in any single event must come from the same external entity so that the Locator provides useful information.

content may be a Unicode string or a byte string; the expat reader module produces always Unicode strings.

parser.setContentHandler( Handler )

设置当前的ContentHandler为我们自己写的handler实例。如果不进行设置,content 事件会被忽略。

参见:https://docs.python.org/2/library/xml.sax.reader.html

XMLReader.setContentHandler(handler)¶
Set the current ContentHandler. If no ContentHandler is set, content events will be discarded.

parser.parse("countries.xml")

开始解析 xml文件。

参见:https://docs.python.org/2/library/xml.sax.reader.html

Process an input source, producing SAX events. The source object can be a system identifier (a string identifying the input source – typically a file name or an URL), a file-like object, or an InputSource object. When parse() returns, the input is completely processed, and the parser object can be discarded or reset. As a limitation, the current implementation only accepts byte streams; processing of character streams is for further study.

python 解析xml 文件: SAX方式的更多相关文章

  1. [转载] python 解析xml 文件: SAX方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  2. python 解析xml 文件: DOM 方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  3. android解析xml文件的方式

    android解析xml文件的方式   作者:东子哥 ,发布于2012-11-26,来源:博客园   在androd手机中处理xml数据时很常见的事情,通常在不同平台传输数据的时候,我们就可能使用xm ...

  4. JAVA解析XML之SAX方式

    JAVA解析XML之SAX方式 SAX解析xml步骤 通过SAXParseFactory的静态newInstance()方法获取SAXParserFactory实例factory 通过SAXParse ...

  5. Java解析XML文件的方式

    在项目里,我们往往会把一些配置信息放到xml文件里,或者各部门间会通过xml文件来交换业务数据,所以有时候我们会遇到“解析xml文件”的需求.一般来讲,有基于DOM树和SAX的两种解析xml文件的方式 ...

  6. python 解析xml 文件: Element Tree 方式

    环境 python:3.4.4 准备xml文件 首先新建一个xml文件,countries.xml.内容是在python官网上看到的. <?xml version="1.0" ...

  7. PYTHON解析XML的多种方式效率对比实测

    在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜索后发现,目前应用比较广泛,且效率相对较高的E ...

  8. 【TensorFlow】Python解析xml文件

    最近在项目中使用TensorFlow训练目标检测模型,在制作自己的数据集时使用了labelimg软件对图片进行标注,产生了VOC格式的数据,但标注生成的xml文件标签值难免会产生个别错误造成程序无法跑 ...

  9. 遍历文件 创建XML对象 方法 python解析XML文件 提取坐标计存入文件

    XML文件??? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 里面的标签都是可以随心所欲的按照他的命名规则来定义的,文件名为roi.xm ...

随机推荐

  1. PropertyPlaceholderConfigurer的用法(使用spring提供的类读取数据库配置信息.properties)

    http://www.cnblogs.com/wanggd/archive/2013/07/04/3172042.html(写的很好)

  2. 删除我的电脑中360随身WiFi云U盘的图标

    可通过删除注册表的方法 运行-regedit 找到这个项 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\My ...

  3. iOS-NSSDate的使用

    取当前时间的秒数 NSTimeInterval time = [[NSDate date] timeIntervalSince1970];long long int date = (long long ...

  4. 设置css三种方法的优先级

    有的小伙伴问了,如果有一种情况:对于同一个元素我们同时用了三种方法设置css样式,那么哪种方法真正有效呢?在下面代码中就出现了这种情况 1.使用内联式CSS设置“超酷的互联网”文字为粉色. 2.然后使 ...

  5. 原生JS判断密码强弱

    前些天工作中有这个需求,自己手写了相关的JS代码,第一种方法是通过ASCII 码判断密码类型,完成用户注册时判断用户输入密码的强度,分强.弱.中三等级,它可以根据用户输入的密码显示对应的密码强弱等级, ...

  6. java 计算器SWT/RAP(版本3)键盘鼠标兼容

    java 计算器SWT/RAP(版本3)键盘鼠标兼容,之前版本也对,但存在线程失效问题,当多人访问时,就容易线程失效,一直犯得一个错误就是一直用static变量和static方法, 之前加了什么js界 ...

  7. 初试ubuntu14.4问题集锦2

    好的,我开始继续鼓捣. 想了这么长时间,我想到的是,肯定是compiz设置了unity的什么东西才导致这种问题,绝非什么显卡驱动的事情. 于是二话不说,开机登录,进入tty1,然后apt-get re ...

  8. 【BZOJ1146】【树链剖分+平衡树】网络管理Network

    Description M 公司是一个非常庞大的跨国公司,在许多国家都设有它的下属分支机构或部门.为了让分布在世界各地的N个部门之间协同工作,公司搭建了一个连接整个公司的通 信网络.该网络的结构由N个 ...

  9. Ubuntu Apache 伪静态配置 url重写 步骤

    1.加载rewrite模块sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.l ...

  10. Joomla插件汉化小程序

    这两天在搞joomla插件,在看peter的视频,在此谢过他了.看到它汉化插件那个视频.反正闲着无聊,就写了一个Java小程序,方便使用joomla的人汉化插件.这个程序的方法很简单,你只要先运行ou ...