Python解析XML字符串
网上查了半天,还就内置的xml.sax轻量级、简便。
鉴于网上的代码哪怕是最简单的示例,也带有很大迷惑性,最后还是自己整理备份一份为好,对于大多数普通情况直接用即可,无须修改。
BTW:还是JSON好用,NND!
[python] www.zzzyk.com
# -*- coding: utf-8 -*-
import xml.sax
import xml.sax.handler
class XMLHandler(xml.sax.handler.ContentHandler):
def __init__(self):
self.buffer = ""
self.mapping = {}
def startElement(self, name, attributes):
self.buffer = ""
def characters(self, data):
self.buffer += data
def endElement(self, name):
self.mapping[name] = self.buffer
def getDict(self):
return self.mapping
data = '''''<?xml version="1.0" encoding="UTF-8"?><note><to>World</to><from>Linvo</from><heading>Hi</heading><body>Hello World!</body></note>'''
xh = XMLHandler()
xml.sax.parseString(data, xh)
ret = xh.getDict()
import pprint
pprint.pprint(ret)
作者:linvo
补充:Web开发 , Python ,