2015-03-02 19 views
0

我有命名空間的XML爲:使用python提取數據的命名空間

<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「)

該文件非常大,包含大量」樣本「標籤。謝謝。

+0

什麼的MD5哈希需要匹配?你是否已經通過其他方式在內存中存儲了一組md5哈希值? – Pete 2015-03-02 22:50:39

+0

是的皮特!我將使用具有md5值的參數進行函數調用。 – Pankaj 2015-03-03 05:51:18

回答

0

謝謝大家!最後我發現如何實現這一點。 DOM在python是最適合做困難的XML操作,需要很多的if/else一種操作:

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)