Python XML 用 ElementTree 解析

Python XML Parsing with ElementTree

首先,我检查了很多关于我遇到的问题的帖子,并尝试了各种方法来获取我需要的值,即使我已经从 XML 文档中识别出我似乎无法识别的标签算出如何打印 <cve>VALUE</cve> 中的值。我看到的所有帖子都与具有属性值的项目相关,并且由于我的标签没有属性值,所以我不确定如何获得我想要的值。

我正在使用 Elementtree 和 python 解析一个 nessus 文件。

我可以识别包含该值的标签,但我无法取出该值,非常令人沮丧。似乎没有属性值(空白),但正如您在 XML 示例中看到的那样,有一个值(但我假设它不是属性值)。任何指针将不胜感激。

例子XML

<SNIP>
<ReportItem port="445" svc_name="cifs" protocol="tcp" severity="0" pluginID="10398" pluginName="Microsoft Windows SMB LsaQueryInformationPolicy Function NULL Session Domain SID Enumeration" pluginFamily="Windows">
<bid>959</bid>
<cve>CVE-2000-1200</cve>
<description>By emulating the call to LsaQueryInformationPolicy() it was possible to obtain the domain SID (Security Identifier).
The domain SID can then be used to get the list of users of the domain</description>
<fname>smb_dom2sid.nasl</fname>
<osvdb>715</osvdb>
<plugin_modification_date>2015/01/12</plugin_modification_date>
<plugin_name>Microsoft Windows SMB LsaQueryInformationPolicy Function NULL Session Domain SID Enumeration</plugin_name>
<plugin_publication_date>2000/05/09</plugin_publication_date>
<plugin_type>local</plugin_type>
<risk_factor>None</risk_factor>
<script_version>$Revision: 1.51 $</script_version>
<solution>n/a</solution>
<synopsis>It is possible to obtain the domain SID.</synopsis>
<xref>OSVDB:715</xref>
<plugin_output>The remote domain SID value is :
FAKESTUFF HERE</plugin_output>
</ReportItem>
<SNIP>

当前代码

import elementtree.ElementTree as ET

def getCVE(nessus_file):
try:
    tree = ET.parse(nessus_file)
    doc = tree.getroot()
    walk = doc.getiterator('cve')
    for cve in walk:
        print cve
except:
    pass


getCVE('file.nessus')

代码的示例输出

<Element cve at 10fd05170>
<Element cve at 10fd20f38>
<Element cve at 10fd2c200>
<Element cve at 10fd3ea70>
<Element cve at 10fd44a70>
<Element cve at 10fd44b00>
<Element cve at 10fd5c170>
<Element cve at 10fd767e8>
<Element cve at 10fdbf290>
<Element cve at 10fdce440>
<Element cve at 10fdce4d0>
<SNIP>

我已经解决了^_^。我只需要文本值 lol YAY!花了几个小时才算出来

所以新的工作代码是

import elementtree.ElementTree as ET

def getCVE(nessus_file):
try:
    tree = ET.parse(nessus_file)
    doc = tree.getroot()
    walk = doc.getiterator('cve')
    for cve in walk:
        print cve.text
except:
    pass

getCVE('file.nessus')