标签:des style blog io color ar for sp strong
python提供了两种解析xml的方式
SAX Simple API for xml
适合解析大型文件,因为解析内容不会保存在内容中,而是在解析到相关内容的时候调用注册的方法
DOM document object model
将整个文档读取到内存中形成一个树形结构
sax解析方式
import xml.sax class MyXmlHandler(xml.sax.ContentHandler): def __init__(self): name="" def startElement(self,tag,attributes): print "startElement tag:"+ tag print attributes def endElement(self,tag): print "endElement tag:" +tag def characters(self,content): #print "charaters:"+self.CurrenntData print content print "" parser = xml.sax.make_parser() # turn off namepsaces #? parser.setFeature(xml.sax.handler.feature_namespaces, 0) Handler = MyXmlHandler() parser.setContentHandler( Handler ) parser.parse("example-req.xml")
DOM的解析方式
要简洁很多
from xml.dom.minidom import parse import xml.dom.minidom DOMTree = xml.dom.minidom.parse("example-req.xml") collection = DOMTree.documentElement ActivityCode=collection.getElementsByTagName("ActivityCode") print ActivityCode[0].childNodes[0].data
标签:des style blog io color ar for sp strong
原文地址:http://www.cnblogs.com/alwaysthinking/p/4067907.html