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

Source: Internet
Author: User
One, the 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)
Gets 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 node's XML representation

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

Second, the Python parsing XML file Instance code
1. Create a User.xml file and add an XML node

Copy the Code code as follows:





Admin
admin@live.cn
23
Man


Admin2
admin2@live.cn
22
Man


Admin3
admin3@live.cn
27
Man


Admin4
admin4@live.cn
25
Woman


Admin5
admin5@live.cn
20
Man


Admin6
admin6@live.cn
23
Woman


2. demo.py parsing user.xml document data

Copy the 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= ' No.:%d\n User name:%s\n Sex:%s\n Age:%s\n Email:%s\n '% (int (user[' id '), user[' username '), user[' sex '], user[' ages ', US er[' email ')
Print User_str
print ' ===================================================== '
if __name__ = = "__main__":
Test_xmltostring ()
Test_laod_xml ()

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

This section is a Python parsing XML python module Xml.dom parsing the contents of the second part of the XML instance.
To perform the printed result:

Copy the Code code as follows:



Admin
admin@live.cn
23
Man


Admin2
admin2@live.cn
22
Man


Admin3
admin3@live.cn
27
Man


Admin4
admin4@live.cn
25
Woman


Admin5
admin5@live.cn
20
Man


Admin6
admin6@live.cn
23
Woman

B. Test parsing XML
The demo.py file is modified into
if __name__ = = "__main__":
Test_laod_xml ()

To print out the results:
-----------------------------------------------------
Item No: 1000001
User name: Admin
Gender: Male
Age: 23
E-mail: admin@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000002
User name: Admin2
Gender: Male
Age: 22
E-mail: admin2@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000003
User name: Admin3
Gender: Male
Age: 27
E-mail: admin3@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000004
User name: Admin4
Gender: Female
Age: 25
E-mail: admin4@live.cn

=====================================================
-----------------------------------------------------
Item No: 1000005
User name: Admin5
Gender: Male
Age: 20
E-mail: admin5@live.cn

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