这几天在忙着绿盟扫描器的事情,今天来了个需求,需要对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 "------------------------ " print "username:"+username+" " print "email:"+email+" " print "age:"+age+" " print "sex:"+sex+" " print "------------------------ "
XML:
<?xml version="1.0" encoding="UTF-8" ?> <users> <user id="1000001"> <username>Admin</username> <email>admin@live.cn</email> <age>23</age> <sex>男</sex> </user> <user id="1000002"> <username>Admin2</username> <email>admin2@live.cn</email> <age>22</age> <sex>男</sex> </user> <user id="1000003"> <username>Admin3</username> <email>admin3@live.cn</email> <age>27</age> <sex>男</sex> </user> <user id="1000004"> <username>Admin4</username> <email>admin4@live.cn</email> <age>25</age> <sex>女</sex> </user> <user id="1000005"> <username>Admin5</username> <email>admin5@live.cn</email> <age>20</age> <sex>男</sex> </user> <user id="1000006"> <username>Admin6</username> <email>admin6@live.cn</email> <age>23</age> <sex>女</sex> </user> </users>