【问题标题】:Parsing xml with python (find tags with specific text)用python解析xml(查找带有特定文本的标签)
【发布时间】:2019-07-01 13:53:57
【问题描述】:

我的任务是处理一个 xml 文件,查找特定元素并将它们导出到 csv 文件中......

我对保存在相同标签中的一些信息特别有问题:

<name>text</name>
<value>value</value>

每个名称标签都包含不同的值,我只需要其中的一些.. 我试过用这段代码循环文件:

try:
        descr = member.find('.//name').text
        if descr == 'description':
            plugin.append(descr)
    except AttributeError:
        descr = 'Unknown'
        plugin.append(descr)

但它只返回“未知”

我的整个代码是这样的(未完成):

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('plugins.xml')
root = tree.getroot()

nessus_out = open('/home/rj/Documents/python/nessus_out.csv', 'w')

csvwriter = csv.writer(nessus_out)

for member in root.findall('nasl'):
    plugin = []

    id = member.find('script_id').text
    plugin.append(id)

    name = member.find('script_name').text
    plugin.append(name)

    family = member.find('script_family').text
    plugin.append(family)

    #for each in member.iterfind('nasl'):
    try:
        solution = member.xpath('.//name/text()')
        if solution == 'solution':
            plugin.append(solution)
    except AttributeError:
        solution = 'Unknown'
        plugin.append(solution)
    csvwriter.writerow(plugin)
nessus_out.close()

最终目标是搜索“解决方案”并从其标签中获取相应的值。

xml结构如下:

nasl_plugins
nasl_plugins/nasl
nasl_plugins/nasl/filename
nasl_plugins/nasl/script_id
nasl_plugins/nasl/script_name
nasl_plugins/nasl/script_family
nasl_plugins/nasl/attributes/attribute/name
nasl_plugins/nasl/attributes/attribute/value

对于丹尼尔:

Xml sn-p:

<nasl>
<filename>fedora_2017-c3149b5fcb.nasl</filename>
<script_id>101028</script_id>
<script_name>Fedora 25 : xen (2017-c3149b5fcb)</script_name>
<script_version>$Revision: 1.5 $</script_version>
<script_copyright>This script is Copyright (C) 2017-2018 Tenable Network Security, Inc.</script_copyright>
<script_family>Fedora Local Security Checks</script_family>
<cves>
 <cve>CVE-2017-10911</cve>
 <cve>CVE-2017-10912</cve>
 <cve>CVE-2017-10913</cve>
 <cve>CVE-2017-10915</cve>
 <cve>CVE-2017-10916</cve>
 <cve>CVE-2017-10917</cve>
 <cve>CVE-2017-10918</cve>
 <cve>CVE-2017-10919</cve>
 <cve>CVE-2017-10920</cve>
 <cve>CVE-2017-10923</cve>
</cves>
<bids>
</bids>
<xrefs>
 <xref>FEDORA:2017-c3149b5fcb</xref>
 <xref>IAVB:2017-B-0074</xref>
</xrefs>
<dependencies>
 <dependency>ssh_get_info.nasl</dependency>
</dependencies>
<required_keys>
 <key>Host/local_checks_enabled</key>
 <key>Host/RedHat/release</key>
 <key>Host/RedHat/rpm-list</key>
</required_keys>
<attribute> 
  <name>plugin_type</name> 
  <value>local</value> 
</attribute> 
<attribute> 
  <name>plugin_modification_date</name> 
  <value>2018/02/02</value> 
</attribute> 
<attribute> 
  <name>stig_severity</name> 
  <value>I</value> 
</attribute> 
<attribute> 
  <name>cvss_base_score</name> 
  <value>10.0</value> 
</attribute> 
</attributes> 

我正在寻找的是 stig_severity、base_cvss_score 和其他一些值的值。所以我的推理是搜索它们,它们向下移动一行并获得值。至于 csv,我需要它在一个线公关插件,所以采用这种格式: id,name,family,solution,description,synopsis,base_cvss_score,plugin_type,stig_severity 然后下一行的下一个插件的值..

【问题讨论】:

  • 我曾经也尝试过用 lxml 做一些事情——放弃了它,而是用 Java 来做。如果您想要更复杂的 xpath 表达式 - 这是最好的方法。
  • Java 对我来说不是一个真正的选择,确实用 bash 尝试过,但它处理大文件真的很糟糕,至少对我来说......
  • 这似乎是一个非常简单的问题,如果没有示例 XML,很难回答。您能否添加一个 XML 的最小示例以及您期望 CSV 的样子? lxml 有很好的 xpath 支持 (1.0) 所以这应该是非常可行的。
  • entrie 文件只是一个接一个列出的插件,带有几乎相同的标签,我需要循环遍历,获取给定 的值,如果它不存在则跳过。然后将其全部导出到 csv 文件。所有插件标签都以 标签开头,并且都包含 script_id/name/family,但其余标签(synopsis、plugin_type 等)并不总是存在于所有插件中,所以我需要能够搜索他们,但如果不存在则跳过..
  • 另外,欢迎来到 Stack Overflow!第一个问题好。 :-)

标签: xml python-3.x csv lxml export-to-csv


【解决方案1】:

看起来您想要的一些值是nasl 的直接子代,而一些在attributes/attribute 中。

可以做的是有两个列表(或元组);一种具有确切的元素名称,另一种具有确切的属性名称 (attribute/name)。

注意:这听起来可能有点令人困惑,因为在这种情况下,“属性名称”实际上是一个名为“属性”的元素,带有一个名为“名称”的子元素,而不是一个名为“名称”的真正 XML 属性。

组合这些元组将为您提供 CSV 中的所有字段。您可以使用它来构建一个包含所有默认值为Unknown 的字段的字典。

然后您可以遍历这两个元组来构建您的两种不同类型的 XPath。如果元素存在,则在字典中更新文本值。否则,该值仍为 Unknown

示例...

XML 输入 (test.xml)

<nasl_plugins>
    <nasl>
        <filename>fedora_2017-c3149b5fcb.nasl</filename>
        <script_id>101028</script_id>
        <script_name>Fedora 25 : xen (2017-c3149b5fcb)</script_name>
        <script_version>$Revision: 1.5 $</script_version>
        <script_copyright>This script is Copyright (C) 2017-2018 Tenable Network Security,
            Inc.</script_copyright>
        <script_family>Fedora Local Security Checks</script_family>
        <cves>
            <cve>CVE-2017-10911</cve>
            <cve>CVE-2017-10912</cve>
            <cve>CVE-2017-10913</cve>
            <cve>CVE-2017-10915</cve>
            <cve>CVE-2017-10916</cve>
            <cve>CVE-2017-10917</cve>
            <cve>CVE-2017-10918</cve>
            <cve>CVE-2017-10919</cve>
            <cve>CVE-2017-10920</cve>
            <cve>CVE-2017-10923</cve>
        </cves>
        <bids> </bids>
        <xrefs>
            <xref>FEDORA:2017-c3149b5fcb</xref>
            <xref>IAVB:2017-B-0074</xref>
        </xrefs>
        <dependencies>
            <dependency>ssh_get_info.nasl</dependency>
        </dependencies>
        <required_keys>
            <key>Host/local_checks_enabled</key>
            <key>Host/RedHat/release</key>
            <key>Host/RedHat/rpm-list</key>
        </required_keys>
        <attributes>
            <attribute>
                <name>plugin_type</name>
                <value>local</value>
            </attribute>
            <attribute>
                <name>plugin_modification_date</name>
                <value>2018/02/02</value>
            </attribute>
            <attribute>
                <name>stig_severity</name>
                <value>I</value>
            </attribute>
            <attribute>
                <name>cvss_base_score</name>
                <value>10.0</value>
            </attribute>
        </attributes>
    </nasl>
</nasl_plugins>

Python 3.x

import csv
from lxml import etree

elem_names = ('script_id', 'script_name', 'script_family')
attr_names = ('solution', 'description', 'synopsis', 'cvss_base_score', 'plugin_type',
              'stig_severity')
field_names = elem_names + attr_names

with open('test.csv', 'w', newline='', encoding='utf8') as xml_data_to_csv:

    csv_writer = csv.DictWriter(xml_data_to_csv, fieldnames=field_names, 
                                quoting=csv.QUOTE_ALL)

    csv_writer.writeheader()

    tree = etree.parse('test.xml')

    for nasl in tree.xpath('.//nasl'):
        # Build a dict containing all of the "field_names" with default values of "Unknown".
        values = {key: 'Unknown' for key in field_names}

        # Process the direct children of "nasl".
        for elem_name in elem_names:
            for child in nasl.xpath(f'*[self::{elem_name}]'):
                values[child.tag] = child.text

        # Process attribute with matching attribute names.
        for attr_name in attr_names:
            for val in nasl.xpath(f'attributes/attribute[name="{attr_name}"]/value'):
                values[attr_name] = val.text

        csv_writer.writerow(values)

输出 (test.csv)

"script_id","script_name","script_family","solution","description","synopsis","cvss_base_score","plugin_type","stig_severity"
"101028","Fedora 25 : xen (2017-c3149b5fcb)","Fedora Local Security Checks","Unknown","Unknown","Unknown","10.0","local","I"

【讨论】:

  • Daniel 你是绝对的冠军.. 非常非常感谢.. 我可以看出我对 lxml 的理解还不够。
猜你喜欢
  • 1970-01-01
  • 2012-04-28
  • 2018-10-31
  • 2016-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 2020-07-23
相关资源
最近更新 更多