我有一个从API获取的具有以下结构的XML-
<entry>
<id>2397</id>
<title>action_alert</title>
<tes:actions>
<tes:name>action_alert</tes:name>
<tes:type>2</tes:type>
</tes:actions>
</entry>
我正在通过以下操作扫描ID-
sourceobject = etree.parse(urllib2.urlopen(fullsourceurl))
source_id = sourceobject.xpath('//id/text()')[0]
我也想得到tes:type
source_type = sourceobject.xpath('//tes:actions/tes:type/text()')[0]
不起作用 它给出以下错误-
lxml.etree.XPathEvalError:未定义的名称空间前缀
如何获取忽略名称空间的信息?
另外,我知道这是命名空间-
<tes:action xmlns:tes="http://www.blah.com/client/servlet">
访问名称空间中节点的正确方法是将前缀名称空间URL映射作为附加参数传递给xpath()
method,例如:
ns = {'tes' : 'http://www.blah.com/client/servlet'}
source_type = sourceobject.xpath('//tes:actions/tes:type/text()', namespaces=ns)
或者,不推荐使用的另一种方法是使用xpath函数忽略名称空间local-name()
:
source_type = sourceobject.xpath('//*[local-name()="actions"]/*[local-name()="type"]/text()')[0]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句