2015-09-28 53 views
2

我想解析一個編碼很差的XML並輸出標籤的節點名稱和內容(只有存在的時候),並且只有當string name = content> 30天)。Python ElementTree - 搜索兒童/孫兒寫作不好的XML

到目前爲止,我可以使用ElementTree搜索子元素,但是我需要幫助解決嵌套不良的信息。我無法更改XML,因爲它是供應商提供的報告。我是一個完整的新手,所以請指導我需要做什麼或提供更好的幫助。提前致謝。

示例文件:

<?xml version="1.0" encoding="UTF-8"?> 
<ReportSection> 
    <ReportHead> 
     <Criteria> 
      <HeadStuff value=Dont Care> 
      </HeadStuff> 
     </Criteria> 
    </ReportHead> 
    <ReportBody> 
     <ReportSection name="UpTime" category="rule"> 
      <ReportSection name="NodeName.domain.net" category="node"> 
       <String name="node">NodeName.domain.net</String> 
       <String name="typeName">Windows Server</String> 
       <OID>-1y2p0ij32e8c8:-1y2p0idhghwg6</OID> 
       <ReportSection name="UpTime" category="element"> 
        <ReportSection name="2015-09-20 18:50:10.0" category="version"> 
         <String name="version">UpTime</String> 
         <OID>-1y2p0ij32e8cj:-1y2p0ibspofhp</OID> 
         <Integer name="changeType">2</Integer> 
         <String name="changeTypeName">Modified</String> 
         <Timestamp name="changeTime" displayvalue="9/20/15 6:50 PM">1442793010000</Timestamp> 
         <ReportSection name="versionContent" category="versionContent"> 
          <String name="content">12 day(s), 7 hour(s), 33 minute(s), 8 second(s)</String> 
          <String name="content"></String> 
         </ReportSection> 
        </ReportSection> 
       </ReportSection> 
      </ReportSection> 
     </ReportSection> 
    </ReportBody> 
</ReportSection> 
+0

什麼是你想要的結果?你有嘗試過什麼嗎?謝謝.. – alecxe

+0

我想返回「節點」值「NodeName.domain.net」,如果值大於30,則返回「12天(s)」的內容。##從xml.etree導入解析器 進口ElementTree的作爲等 ##設置xml文件並解析它 根= et.parse( 'C:\\溫度\\掃描\\ report.xml將') 用於SEC1在root.iter(): \t Sec1Name = Sec1.attrib.get('name') \t print(Sec1Name) – KFrizz

回答

2

的想法是找到content節點,提取多少天都在那裏,然後檢查所需的值,並找到節點名。示例(使用lxml.etree):

import re 

from lxml import etree 

pattern = re.compile(r"^(\d+) day\(s\)") 

data = """your XML here""" 
tree = etree.fromstring(data) 

content = tree.findtext(".//String[@name='content']") 
if content: 
    match = pattern.search(content) 
    if match: 
     days = int(match.group(1)) 

     # TODO: check the days if needed 

     node = tree.findtext(".//String[@name='node']") 

     print node, days 

打印:

NodeName.domain.net 12 
+0

如果上面的例子重複幾千次,這個工作是否會起作用? node1,node2,node3在xml的深度中發生變化。 – KFrizz

+0

@KFrizz不在這個狀態。您基本上需要遍歷'ReportSection'節點,併爲循環中的每個「ReportSection」創建特定於上下文的代碼。你應該在問題中說明它。我認爲答案對你來說是一個好的開始,你會改進它以支持多個「ReportSection」節點。 – alecxe