之前在使用xml解析的时候,在网上搜了很多教程,最终没有能按照网上的教程实现需求。
所以呢,只好自己去看源码,在sax的__init__.py下看到这么一段代码:
1 def parse(source, handler, errorHandler=ErrorHandler()):
2 parser = make_parser()
3 parser.setContentHandler(handler)
4 parser.setErrorHandler(errorHandler)
5 parser.parse(source)
# 可以看出来,执行xml解析至少需要两个参数:source:源文件路径和实例化的handler对象
下面我们就用一个例子来是实现一下:(事先说明,这个例子是网上找的,不是自己写的)
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
下面将对各个步骤的作用逐个说明:
#!usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/5/30 22:43
# @Author : Adong_Chen from xml import sax class TestHandler(sax.ContentHandler): # 定义自己的handler类,继承sax.ContentHandler
def __init__(self):
sax.ContentHandler.__init__(self) # 弗父类和子类都需要初始化(做一些变量的赋值操作等)
self._content = ""
self._tag = "" def startElement(self, name, attrs): # 遇到<tag>标签时候会执行的方法,这里的name,attrs不用自己传值的(这里其实是重写)
self._tag = name
if name == "bookstore":
print "=========BOOKSTORE========="
if self._tag == "book":
print "BOOK: " + attrs["category"]
print "--------------------------" def endElement(self, name): # 遇到</tag>执行的方法,name不用自己传值(重写)
# print "endElement"
if name == "bookstore":
print "=========BOOKSTORE========="
elif name == "title":
print "Title: " + self._content
elif name == "author":
print "Author: " + self._content
elif name == "year":
print "Year: " + self._content
elif name == "price":
print "Price: " + self._content
else:
pass def characters(self, content): # 获取标签内容
self._content = content if __name__ == "__main__":
handler = TestHandler() # 自定义类实例化成对象
sax.parse("Test2.xml", handler) # 解析xml文件
执行结果如下:
=========BOOKSTORE=========
BOOK: CHILDREN
--------------------------
Title: Harry Potter
Author: J K. Rowling
Year: 2005
Price: 29.99
BOOK: WEB
--------------------------
Title: Learning XML
Author: Erik T. Ray
Year: 2003
Price: 39.95
=========BOOKSTORE=========