Parse XML files using Python

Source: Internet
Author: User

Python file: CopyCode The Code is as follows: # parsexml. py
# In this example, the python online document has been modified and added.

Import XML. parsers. Expat

# Control print indentation
Level = 0

# Obtain a node name and a set of attribute values
Def start_element (name, attrs ):
Global level
Print ''' * level, 'start element: ', name, attrs
Level = level + 1

# Obtain the end name of a node
Def end_element (name ):
Global level
Level = level-1
Print ''' * level, 'end element: ', name

# Obtain the Intermediate Value of a node
Def char_data (data ):
If (Data = '\ n '):
Return
If (data. isspace ()):
Return
Global level
Print ''' * level, 'character data: ', Data

P = xml. parsers. Expat. parsercreate ()

P. startelementhandler = start_element
P. endelementhandler = end_element
P. characterdatahandler = char_data
P. returns_unicode = false

F = file ('sample. xml ')
P. parsefile (f)
F. Close ()

XML file (sample. XML ):Copy codeThe Code is as follows: <contacts id = "bluecrystal">
<Item name = "Keen" fff = "DDD">
<Telephone type = "phone"> 222222222 </telephone>
<Telephone type = "mobile"> 134567890 </telephone>
</Item>
<Item name = "BCM">
<Telephone type = "phone"> 11111111 </telephone>
<Telephone type = "mobile"> 15909878909 </telephone>
</Item>
</Contacts>

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: info-contact@alibabacloud.com 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.