Python parsing XML python module xml.dom parsing XML Instance code _python

Source: Internet
Author: User

One, Python module xml.dom parsing XML API

Minidom.parse (filename)
Load read XML file

Doc.documentelement
Get XML Document Object

Node.getattribute (AttributeName)
Get XML Node Property value

Node.getelementsbytagname (TagName)
Getting the collection of XML node objects

Node.childnodes #返回子节点列表.

Node.childnodes[index].nodevalue
Get XML node value

Node.firstchild
#访问第一个节点. Equivalent to Pagexml.childnodes[0]

doc = minidom.parse (filename)
Doc.toxml (' UTF-8 ')
Returns the text of the XML representation of node nodes

node.attributes["id"]
A.name #就是上面的 "id"
A.value #属性的值
accessing element properties

Second, Python parse the XML file instance code
1, create User.xml file, add XML node

Copy Code code 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> Women </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> Women </sex>
</user>
</users>

2, demo.py parsing user.xml document data

Copy Code code as follows:

#-*-Coding:utf-8-*-
"""
* user:lhj588
* Date:11-11-9
* TIME:13:20
* 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.documentelement
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= ' ID:%d\n username:%s\n Sex:%s\n Age:%s\n mailbox:%s\n '% (int (user[' id ')), user[' username '], user[' sex '], user[' AG E '], user[' email ']
Print User_str
print ' ===================================================== '
if __name__ = = "__main__":
Test_xmltostring ()
Test_laod_xml ()

3. Test effect
A, Test ToXml
The demo.py file is modified into
if __name__ = = "__main__":
Test_xmltostring ()

This section is the content of the second part of the Python parsing XML Python module xml.dom parsing XML instances.
To perform the print result:

Copy Code code 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> Women </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> Women </sex>
</user>

B, test parse XML
The demo.py file is modified into
if __name__ = = "__main__":
Test_laod_xml ()

Perform print out results:
-----------------------------------------------------
Item No: 1000001
User name: Admin
Sex: Male
Age: 23
Email: admin@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000002
User name: Admin2
Sex: Male
Age: 22
Email: admin2@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000003
User name: Admin3
Sex: Male
Age: 27
Email: admin3@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000004
User name: Admin4
Sex: Female
Age: 25
Email: admin4@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000005
User name: Admin5
Sex: Male
Age: 20
Email: admin5@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000006
User name: Admin6
Sex: Female
Age: 23
Email: 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.