2011-03-25 57 views
1

我試圖找到所有子元素的屬性class是'TRX',其屬性distName以'PLMN-PLMN/BSC-208812/BCF-1/BTS-1開始'元素樹搜索幫助(python,xml)

是這樣的可能嗎?

root[0].findall("*[@class='TRX'][@distName='PLMN-PLMN/BSC-208812/BCF-1/BTS-1*']") 

我在lxml上使用cElementTree,因爲它比我的comp上快得多。

回答

2

ElementTree實際上可以做到這一點。

您可能需要使用.//*而不是*

Python docs ElementTree版本1.3.0隨Python 2.7一起提供了您尋求的XPath功能。

from xml.etree import ElementTree 

et = ElementTree.fromstring(""" 
<r> 
    <b> 
     <a class='c' foo='e'>this is e</a> 
     <a class='c' foo='f'>this is f</a> 
     <a class='c' foo='g'>this is g</a> 
    </b> 
</r> 
""") 


if __name__ == '__main__': 
    print ElementTree.VERSION 
    print "* c and f", et.findall("*[@class='c'][@foo='f']") 
    print ".//* c and f", et.findall(".//*[@class='c'][@foo='f']") 
    print ".//* c", et.findall(".//*[@class='c']") 
    print ".//* f", et.findall(".//*[@foo='f']") 

輸出

1.3.0 
* c and f [] 
.//* c and f [<Element 'a' at 0x10049be50>] 
.//* c [<Element 'a' at 0x10049bdd0>, <Element 'a' at 0x10049be50>, <Element 'a' at 0x10049bf10>] 
.//* f [<Element 'a' at 0x10049be50>] 
+0

我想我misphrased我的問題,我想找到的所有類= 'C',其 foo的屬性開始的東西 – jck 2011-03-25 10:03:48

+0

我的壞,我沒有讀過它。 http://effbot.org/zone/element-xpath.htm顯示它不支持starts-with(),這是你需要的。 – kevpie 2011-03-25 10:19:07

+0

我通過在Python中迭代循環來完成它...由於xml的結構,它仍然比lxml更快...... – jck 2011-03-25 12:02:58