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>