Parse XML strings using Python

Source: Internet
Author: User
Tags pprint
Parse XML strings using Python
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!

#-*-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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.