2013-08-07 21 views
1

我想使用Python(2.7.5)ElementTree通過多個搜索條件從xml文件中提取一些元素。 的XML是什麼樣子:如何在Python元素樹中處理xpath的多個搜索條件

<src name="BdsBoot.c"> 
     <fn name="XXXXX" fn_cov="0" fn_total="1" cd_cov="0" cd_total="4"> 
      <probe line="113" kind="condition" event="full"/> 
      <probe line="122" column="10" kind="condition" event="none" /> 
      <probe line="124" column="9" kind="condition" event="full" /> 
     </fn> 
    </src> 

我想要的那種= 「條件」 和事件= 「滿」

我有

root.findall(".//probe[@kind='condition' and @event='full']") —— error 
root.findall(".//probe[@kind='condition'] and .//probe[@event='full']") —— nothing 

我讀了簡單的介紹試圖探頭元件here ,現在似乎elementtree不支持和運營商?

有什麼辦法可以達到這個目標嗎?

回答

3

使用這一個:

root.findall('.//probe[@kind="condition"][@event="full"]') 

演示:

>>> s 
'<src name="BdsBoot.c">\n  <fn name="XXXXX" fn_cov="0" fn_total="1" cd_cov="0" cd_total="4">\n   <probe line="113" kind="condition" event="full"/>\n   <probe line="122" column="10" kind="condition" event="none" />\n   <probe line="124" column="9" kind="condition" event="full" />\n  </fn>\n </src>' 
>>> root = ET.fromstring(s) 
>>> root.findall('.//probe[@kind="condition"]') 
[<Element 'probe' at 0x7f8a5146ce10>, <Element 'probe' at 0x7f8a5146ce50>, <Element 'probe' at 0x7f8a5146ce90>] 
>>> root.findall('.//probe[@kind="condition"][@event="full"]') 
[<Element 'probe' at 0x7f8a5146ce10>, <Element 'probe' at 0x7f8a5146ce90>] 
+0

O.o..thank你它的作品! – ygg

+0

我有一個新問題,如何使用'..'來訪問父節點? – ygg

+0

你最好發表一個新問題。 :(因爲你的一句話評論中的信息很少,我不知道如何回答, – zhangyangyu