2012-02-17 36 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]