Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1276349
  • 博文数量: 185
  • 博客积分: 50
  • 博客等级: 民兵
  • 技术积分: 3934
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-11 13:11
个人简介

iihero@ChinaUnix, ehero.[iihero] 数据库技术的痴迷爱好者. 您可以通过iihero AT qq.com联系到我 以下是我的三本图书: Sybase ASE in Action, Oracle Spatial及OCI高级编程, Java2网络协议内幕

文章分类

全部博文(185)

文章存档

2014年(4)

2013年(181)

分类: Python/Ruby

2013-07-18 09:49:52

首先,sax解析最直观,当然,也可以容许xml文件出些错。

先给定一个xml文件book.xml, 

<catalog>
  
<book isbn="0-596-00128-2">
    
<title>Python & XMLtitle>
    
<author>Jones, Drakeauthor>
  
book>
  
<book isbn="0-596-00085-5">
    
<title>Programming Pythontitle>
    
<author>Lutzauthor>
  
book>
   
<book isbn="0-596-00281-5">
    
<title>Learning Pythontitle>
    
<author>Lutz, Ascherauthor>
  
book>
   
<book isbn="0-596-00797-3">
    
<title>Python Cookbooktitle>
    
<author>Martelli, Ravenscroft, Ascherauthor>
  
book>
 

catalog>

写一个BookHandler, 如下:

 

# -*- coding: utf-8 -*-

import xml.sax.handler

class BookHandler(xml.sax.handler.ContentHandler):
  
def __init__(self):
    self.inTitle 
= 0                                # handle XML parser events
    self.mapping = {}                               # a state machine model

  
def startElement(self, name, attributes):
    
if name == "book":                              # on start book tag
      self.buffer = ""                              # save ISBN for dict key
      self.isbn = attributes["isbn"]
    
elif name == "title":                           # on start title tag
      self.inTitle = 1                              # save title text to follow

  
def characters(self, data):
    
if self.inTitle:                                # on text within tag
      self.buffer += data                           # save text if in title

  
def endElement(self, name):
    
if name == "title":
      self.inTitle 
= 0                              # on end title tag
      self.mapping[self.isbn] = self.buffer         # store title text in dict

import xml.sax
import pprint

parser 
= xml.sax.make_parser( )
handler 
= BookHandler( )
parser.setContentHandler(handler)
parser.parse(
'book.xml')

pprint.pprint(handler.mapping)

      

结果如下:

Process started >>>
{u'0-596-00085-5': u'Programming Python',
 u'0-596-00128-2': u'Python & XML',
 u'0-596-00281-5': u'Learning Python',
 u'0-596-00797-3': u'Python Cookbook'}<<< Process finished.
================ READY ================

不过,这是比较简单的情况了。而且我们可以看到,结果全是以unicode串输出的。

阅读(2303) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~