2011-02-16 17 views
3


我使用ElementTree(1.3)與Python 2.7和享受的XPath功能,
但是一個搜索結果出乎我的意料。ElementTree的XPath的奇怪行爲

我的XML例子:

<OTF> 
    <FECS state="disabled" version="2.2.0.0"> 
    <BackEndCompatibility major="2.2" state="disabled"> 
     <BackEnd state="disabled" version="2.2.0.0"/> 
    </BackEndCompatibility> 
    </FECS> 
</OTF> 

問題1:
當我使用findall獲得第一個找到的元素

version = "2.2.0.0" 
found = list(txml.findall(".//BackEnd[@version='%s']" % version)) 
return found and found[0] or None 

發現什麼。

但是當我改變XML文件,這樣BackEnd元素包含子元素

 <BackEnd state="disabled" version="2.2.0.0"> 
      <any_dummy_element/> 
     </BackEnd> 

然後搜索元素被正確發現。

您是否面對這樣的行爲?
我在做錯什麼,或者這是ElementTree執行中的錯誤?

問題2:
另一個問題我已經是xmlns
假設我改變XML第一行包含xmlns

<OTF xmlns="http://si-wiki/OTFCompatibility"> 
</OTF> 

在我必須找到字符串改變這樣的情況:

".//{http://si-wiki/OTFCompatibility}BackEnd[@version='%s']" 

有沒有辦法告訴ElementTree的過程中忽略的xmlns解析和處理所有元素的名稱(包括根),就像他們沒有前綴一樣?

問候,
茲比格涅夫·

回答

1

對於問題NO1:
當我更換線

found = list(txml.findall(".//BackEnd[@version='%s']" % version)) 
    return found and found[0] or None 

found = txml.findall(".//BackEnd[@version='%s']" % version) 
    if found: 
     return found[0] 
    return None 

然後在不啞的孩子劈返回正確的結果。