2012-02-17 134 views
1
找到元素屬性

想我已在下面的XML:如何使用LXML

<package xmlns="http://example/namespace"> 
    <rating system="au-oflc">PG</rating> 
    ... 
</package> 

獲取元素的文字在上面,我做了以下內容:

from lxml import entree 
f = open('/Users/David/Desktop/metadata.xml') 
metadata_contents = f.read() 
node = etree.fromstring(metadata_contents) 
rating = node.xpath('//t:rating/text()', namespaces = {'t':'http://example/namespace'}) 
>>> rating 
['PG'] 

如何我會得到「au-oflc」的價值嗎?

回答

6

您需要檢索節點本身,而不是它的文本:

rating = node.xpath('//t:rating', namespaces = {'t':'http://example/namespace'}) 
print rating[0].attrib['system'] 
1

您也可以訪問屬性使用XPath:

system = node.xpath('//t:rating/@system', namespaces = {'t':'http://example/namespace'}) 
print system[0]