-
Parse XML strings using Python
-
13:30:28
-
Add to favorites I want to contribute
After checking the web for half a day, the built-in XML. Sax is lightweight and simple.
Given that even the simplest examples of code on the Internet are confusing, it is better to organize and back up a copy by yourself. In most common cases, you can use it directly without modifying it.
BTW: JSON is easy to use, nnd!
[Python] www.2cto.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>
XH = xmlhandler ()
XML. Sax. parsestring (data, XH)
Ret = XH. getdict ()
Import pprint
Pprint. pprint (RET)