【问题标题】:using python extract data from xml having xmlns namespace使用python从具有xmlns命名空间的xml中提取数据
【发布时间】:2015-05-03 07:31:24
【问题描述】:

我有一个具有命名空间的 XML:

<metadata xmlns="http://example.com">


<samples>
<sample>

    <hashes>
        <hash type="md5">Abc6FC6F4AA4C5315D2A52E29865F7F6</hash>
    </hashes>


    <detections>

        <detection vendor="example_1" date="2015-02-17T01:55:38" type="human" >

            <![CDATA[my_detection1]]>

        </detection>

        <detection vendor="example_2" date="2015-02-17T01:55:38" type="computer" >

            <![CDATA[my_detection2]]>


        </detection>

    </detections>
</sample>

<sample>

    <hashes>
        <hash type="md5">CDEFC6F4AA4C5315D2A52E29865F7F6</hash>
    </hashes>


    <detections>

        <detection vendor="example_3" date="2015-02-17T01:55:38" type="human" >

              <![CDATA[my_detection3]]>

        </detection>

        <detection vendor="example_4" date="2015-02-17T01:55:38" type="computer" >

              <![CDATA[my_detection4]]>

        </detection>

    </detections>
</sample>
</samples>
</metadata>

我想提取这样的数据:

如果特定的“md5”匹配,则检查“检测”中的“供应商”属性,如果匹配,则提取属性“日期”和文本值(例如:“my_detection1”)

该文件将非常大,其中包含大量“示例”标签。谢谢。

【问题讨论】:

  • md5 哈希需要匹配什么?您是否已经通过其他方式将一组 md5 哈希值保存在内存中?
  • 是的,皮特!我将使用具有 md5 值的参数进行函数调用。

标签: python xml namespaces


【解决方案1】:

谢谢大家!最后我找到了如何实现这一点。 python 中的 DOM 最适合执行需要大量 if/else 操作的困难 XML 操作:

import xml.dom.minidom
from xml.dom.minidom import Node

dom = xml.dom.minidom.parse("C:/tmp/merged.xml")

hash_node=dom.getElementsByTagName('hash')

md5='7CD6FC6F4AA4C5315D2A52E29865F7F6'

for node1 in hash_node:

    str1 = node1.childNodes[0].wholeText

    if (str1 == md5):

        hashes_node = node1.parentNode
        sample_node = hashes_node.parentNode
        detection_node = sample_node.getElementsByTagName('detection')


        print ("For MD5 " + md5 + ",\n\n")
        for node2 in detection_node:

            print (node2.childNodes[0].wholeText)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多