# -*- coding:utf-8 -*- __author__ = ‘magicpwn‘ from xml.etree import ElementTree # 向parse()传递一个打开的文件句柄 ,读取解析并返回一个Elementtree对象 with open(‘C:/XML/6.xml‘, ‘rt‘) as f: tree = ElementTree.parse(f) #print tree # 遍历解析树,实用iter()创建一个生成器,迭代处理Elementtree实例 # ElementTree元素树 和 Element元素 是不同的类,对象方法也不同 count = 0 for node in tree.iter(): if node.tag == ‘cve‘: print ‘===========================================‘ print node.tag, node.attrib # 获取到了参数字典 count += 1 # help(ElementTree) # help(ElementTree.Element) print count >>> =========================================== cve {‘cve-status‘: ‘‘, ‘cve-name‘: ‘CVE-2015-0006‘} =========================================== cve {‘cve-status‘: ‘‘, ‘cve-name‘: ‘CVE-2015-0011‘} 2
将打开的xml文件parse为ElementTree对象。
可以通过ElementTree访问tree的节点元素。
可以通过节点元素,访问节点元素的元素名,属性字典等
如:
<vuln vuln-id="73863" vuln-name="Microsoft Windows TrueType远程代码执行漏洞(MS12-078)" vuln-severity="3" vuln-value="3"> <asset-IP>192.168.28.23</asset-IP> <asset-port>0</asset-port> <port-type>其他</port-type> <asset-protocol /> <asset-service /> <system-affected>Microsoft Windows XP SP2 and SP3, Windows Server 2003 SP2, Windows Vista SP2, Windows Server 2008 SP2, R2, and R2 SP1, Windows 7 Gold and SP1, Windows 8, Windows Server 2012, and Windows RT</system-affected> - <remedy> <![CDATA[ 建议您采取以下措施进行修补以降低威胁: <br/> <br/>目前厂商已经发布了升级补丁以修复此安全问题,补丁获取链接: <br/> <br/><a href=‘http://technet.microsoft.com/zh-cn/security/bulletin/MS12-078‘ style=‘color:#0000fe;text-decoration:underline;‘ target=‘_blank‘>http://technet.microsoft.com/zh-cn/security/bulletin/MS12-078</a> </remedy> - <description> <![CDATA[ 受影响的组件处理特制 TrueType 字体文件的方式中存在一个远程执行代码漏洞。如果用户打开特制的 TrueType 字体文件,该漏洞可能允许远程执行代码。 </description> - <cve cve-name="CVE-2012-4786" cve-status=""> - <cve-desc> <![CDATA[ The kernel-mode drivers in Microsoft Windows XP SP2 and SP3, Windows Server 2003 SP2, Windows Vista SP2, Windows Server 2008 SP2, R2, and R2 SP1, Windows 7 Gold and SP1, Windows 8, Windows Server 2012, and Windows RT allow remote attackers to execute arbitrary code via a crafted TrueType Font (TTF) file, aka "TrueType Font Parsing Vulnerability." </cve-desc> </cve> <cncve>CNCVE-20124786</cncve> </vuln>
这个元素内含多个子元素,该元素<vuln>属性在头部括号内,通过节点attrib字段,可以访问属性字典。通过tag字段访问标记名称,通过text访问值,通过tail读末尾的文本(结束标记之后,下一开始标记或父元素标记结束之前)
本文出自 “magicpwn” 博客,请务必保留此出处http://magicpwn.blog.51cto.com/10497784/1682404
原文地址:http://magicpwn.blog.51cto.com/10497784/1682404