python 解析XML

这几天在忙着绿盟扫描器的事情,今天来了个需求,需要对API返回的XML进行解析.并读取指定数据.

于是就有了这么个脚本.本来准备用Perl写,但是不知道为什么Perl链接HTTPS时,总说有错误.

所以就用这个不太熟悉的语言来写了,Python写得不多,今天也就尝试尝试...

写了1个多小时,初步学会了怎么分析XML.明天实地测试下,看看好不好用吧..

#!/usr/bin/python

# -*- coding:utf-8 -*-
from xml.dom import minidom

dom=minidom.parse('1.xml')

root=dom.documentElement

def getEname(item,tag):
        return item.getElementsByTagName(tag)[0].firstChild.nodeValue

for item in root.getElementsByTagName('user'):
        username=getEname(item,'username')
        email=getEname(item,'email')
        age=getEname(item,'age')
        sex=getEname(item,'sex')
        print "------------------------\n"
        print "username:"+username+"\n"
        print "email:"+email+"\n"
        print "age:"+age+"\n"
        print "sex:"+sex+"\n"
        print "------------------------\n"

XML:

<?xml version="1.0" encoding="UTF-8" ?>
<users>
    <user id="1000001">
        <username>Admin</username>
        <email>[email protected]</email>
        <age>23</age>
        <sex></sex>
    </user>
    <user id="1000002">
        <username>Admin2</username>
        <email>[email protected]</email>
        <age>22</age>
        <sex></sex>
    </user>
    <user id="1000003">
        <username>Admin3</username>
        <email>[email protected]</email>
        <age>27</age>
        <sex></sex>
    </user>
    <user id="1000004">
        <username>Admin4</username>
        <email>[email protected]</email>
        <age>25</age>
        <sex></sex>
    </user>
    <user id="1000005">
        <username>Admin5</username>
        <email>[email protected]</email>
        <age>20</age>
        <sex></sex>
    </user>
    <user id="1000006">
        <username>Admin6</username>
        <email>[email protected]</email>
        <age>23</age>
        <sex></sex>
    </user>
</users>

 

你可能感兴趣的:(python 解析XML)