2013-04-11 18 views
0

我使用下面的python代碼做xpath屬性查找,但得到一個錯誤:
selector.append(ops [token [0]](next,token )) KeyError異常: '@'
只是用starndard python2.7版本,沒有額外的模塊如何在python中使用xpath列出屬性值

的xml文件看起來像:

<rule-set> 
<rule name="firstRule" salience="3" /> 
<rule name="secondRule" salience="5" /> 
</rule-set> 

我的代碼如下所示:

import xml.etree.ElementTree as ET 
fp = open("./rules.xml", "r") 
elementTree = ET.parse(fp) 
e = elementTree.findall('rule') #looking up element, this works 
for i in e: 
    print i.attrib 
e = elementTree.findall('rule/@salience') #directly looking up attribute fails 
for i in e: 
    print i 
print 'all done' 

我有點困惑,...我認爲這個xpath查找將支持xpath1.0,或者我做錯了什麼?

回答

0

docs

This module provides limited support for XPath expressions for locating elements in a tree. The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module.

xml.etree模塊不允許直接使用它的xpath syntax,只選擇具有某些屬性的元素選擇屬性。

如果您想要更完整的xpath支持,您應該查看lxmletree