標籤:python xml
# -*- 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 = 0for 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
python處理XML解析(讀取)