Python parsing XML python module xml. dom parsing xml instance code

Source: Internet
Author: User

I. python module xml. dom parsing XML API

Minidom. parse (filename)
Load and read XML files

Doc.doc umentElement
Get XML document objects

Node. getAttribute (AttributeName)
Get XML node attribute values

Node. getElementsByTagName (TagName)
Get XML Node object set

Node. childNodes # Return to the subnode list.

Node. childNodes [index]. nodeValue
Get XML node Value

Node. firstChild
# Access the first node. Equivalent to pagexml. childNodes [0]

Doc = minidom. parse (filename)
Doc. toxml ('utf-8 ')
Returns the xml Representation of the Node.

Node. attributes ["id"]
A. name # Is the above "id"
A. value # Attribute value
Access element attributes

Ii. Example code for parsing xml files using python
1. Create a user. xml file and add an XMl node.

Copy codeThe Code is as follows:
<? Xml version = "1.0" encoding = "UTF-8"?>
<Users>
<User id = "1000001">
<Username> Admin </username>
<Email> admin@live.cn </email>
<Age> 23 </age>
<Sex> male </sex>
</User>
<User id = "1000002">
<Username> Admin2 </username>
<Email> admin2@live.cn </email>
<Age> 22 </age>
<Sex> male </sex>
</User>
<User id = "1000003">
<Username> Admin3 </username>
<Email> admin3@live.cn </email>
<Age> 27 </age>
<Sex> male </sex>
</User>
<User id = "1000004">
<Username> Admin4 </username>
<Email> admin4@live.cn </email>
<Age> 25 </age>
<Sex> female </sex>
</User>
<User id = "1000005">
<Username> Admin5 </username>
<Email> admin5@live.cn </email>
<Age> 20 </age>
<Sex> male </sex>
</User>
<User id = "1000006">
<Username> Admin6 </username>
<Email> admin6@live.cn </email>
<Age> 23 </age>
<Sex> female </sex>
</User>
</Users>

2. Demo. py parses user. xml document data

Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
"""
* User: lhj588
* Date: 11-11-9
* Time:
* Desc:
"""
From xml. dom import minidom
Def get_attrvalue (node, attrname ):
Return node. getAttribute (attrname) if node else''
Def get_nodevalue (node, index = 0 ):
Return node. childNodes [index]. nodeValue if node else''
Def get_xmlnode (node, name ):
Return node. getElementsByTagName (name) if node else []
Def xml_to_string (filename = 'user. xml '):
Doc = minidom. parse (filename)
Return doc. toxml ('utf-8 ')
Def get_xml_data (filename = 'user. xml '):
Doc = minidom. parse (filename)
Root = doc.doc umentElement
User_nodes = get_xmlnode (root, 'user ')
User_list = []
For node in user_nodes:
User_id = get_attrvalue (node, 'id ')
Node_name = get_xmlnode (node, 'username ')
Node_email = get_xmlnode (node, 'email ')
Node_age = get_xmlnode (node, 'age ')
Node_sex = get_xmlnode (node, 'sex ')
User_name = get_nodevalue (node_name [0]). encode ('utf-8', 'ignore ')
User_email = get_nodevalue (node_email [0]). encode ('utf-8', 'ignore ')
User_age = int (get_nodevalue (node_age [0])
User_sex = get_nodevalue (node_sex [0]). encode ('utf-8', 'ignore ')
User = {}
User ['id'], user ['username'], user ['email '], user ['age'], user ['sex'] = (
Int (user_id), user_name, user_email, user_age, user_sex
)
User_list.append (user)
Return user_list
Def test_xmltostring ():
Print xml_to_string ()
Def test_laod_xml ():
User_list = get_xml_data ()
For user in user_list:
# Print user ['sex']
Print '-----------------------------------------------------'
If user:
User_str = 'Code: % d \ n Username: % s \ n sex: % s \ n age: % s \ n mail box: % s \ n' % (int (user ['id']), user ['username'], user ['sex'], user ['age'], user ['email '])
Print user_str
Print '============================================== =================='
If _ name _ = "_ main __":
Test_xmltostring ()
Test_laod_xml ()

3. Test Results
A. Test toxml
Modify the demo. py file
If _ name _ = "_ main __":
Test_xmltostring ()

This section describes how to use python to parse the second part of the XML python module xml. dom to parse the xml instance.
Print the result:

Copy codeThe Code is as follows:
<User id = "1000001">
<Username> Admin </username>
<Email> admin@live.cn </email>
<Age> 23 </age>
<Sex> male </sex>
</User>
<User id = "1000002">
<Username> Admin2 </username>
<Email> admin2@live.cn </email>
<Age> 22 </age>
<Sex> male </sex>
</User>
<User id = "1000003">
<Username> Admin3 </username>
<Email> admin3@live.cn </email>
<Age> 27 </age>
<Sex> male </sex>
</User>
<User id = "1000004">
<Username> Admin4 </username>
<Email> admin4@live.cn </email>
<Age> 25 </age>
<Sex> female </sex>
</User>
<User id = "1000005">
<Username> Admin5 </username>
<Email> admin5@live.cn </email>
<Age> 20 </age>
<Sex> male </sex>
</User>
<User id = "1000006">
<Username> Admin6 </username>
<Email> admin6@live.cn </email>
<Age> 23 </age>
<Sex> female </sex>
</User>

B. Test parsing XML
Modify the demo. py file
If _ name _ = "_ main __":
Test_laod_xml ()

Run the following command to print the result:
-----------------------------------------------------
Code: 1000001
Username: Admin
Sex: Male
Age: 23
Mail: admin@live.cn

========================================================== ==================
-----------------------------------------------------
Code: 1000002
Username: Admin2
Sex: Male
Age: 22
Mail: admin2@live.cn

========================================================== ==================
-----------------------------------------------------
Code: 1000003
Username: Admin3
Sex: Male
Age: 27
Mail: admin3@live.cn

========================================================== ==================
-----------------------------------------------------
Code: 1000004
Username: Admin4
Sex: Female
Age: 25
Mail: admin4@live.cn

========================================================== ==================
-----------------------------------------------------
Code: 1000005
Username: Admin5
Sex: Male
Age: 20
Mail: admin5@live.cn

========================================================== ==================
-----------------------------------------------------
Code: 1000006
Username: Admin6
Sex: Female
Age: 23
Mail: admin6@live.cn

========================================================== ==================

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.