首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用python解析xml (查找带有特定文本的标记)

用python解析xml (查找带有特定文本的标记)
EN

Stack Overflow用户
提问于 2019-02-07 12:35:57
回答 1查看 2.3K关注 0票数 3

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

我在某些信息上遇到了困难,这些信息是相同标签上的:

代码语言:javascript
复制
<name>text</name>
<value>value</value>

每个名称标签包含不同的值,我只需要其中的一些。我尝试用下面的代码循环这个文件:

代码语言:javascript
复制
try:
        descr = member.find('.//name').text
        if descr == 'description':
            plugin.append(descr)
    except AttributeError:
        descr = 'Unknown'
        plugin.append(descr)

但它只返回“未知”

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

代码语言:javascript
复制
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结构如下:

代码语言:javascript
复制
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片段:

代码语言:javascript
复制
<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和som等的价值。所以我的理由是去寻找,然后他们沿着一条线移动,得到价值。至于csv,我需要它在一个线公关。插件,所以在这种格式:id,name,family,solution,description,synopsis,base_cvss_score,plugin_type,stig_severity,然后值下一行的下一个插件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-07 23:11:52

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

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

注意:这听起来可能有点混乱,因为在本例中,“属性名称”实际上是一个名为" attribute“的元素,其子元素名为"name”,而不是真正的名为"name“的XML属性。

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

然后可以迭代两个元组来构建两种不同类型的XPaths。如果元素存在,则在dict中更新文本值。否则,该值将保持为Unknown

例如..。

XML输入 (test.xml)

代码语言:javascript
复制
<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>

Python3.x

代码语言:javascript
复制
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)

代码语言:javascript
复制
"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"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54573496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档