Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python lxml-xpath的语法问题_Python_Xpath_Lxml - Fatal编程技术网

Python lxml-xpath的语法问题

Python lxml-xpath的语法问题,python,xpath,lxml,Python,Xpath,Lxml,在用lxml解析Python中的XML时,我很难理解用于获取单个元素的正确语法 当我这样做时: print self.root.xpath("descendant::*[@Name='GevCCP']/*",namespaces=self.nsmap) 我得到一个下级节点列表: [<Element {http://www.genicam.org/GenApi/Version_1_0}ToolTip at 0x1175830>, <Element {http://www.gen

在用lxml解析Python中的XML时,我很难理解用于获取单个元素的正确语法

当我这样做时:

print self.root.xpath("descendant::*[@Name='GevCCP']/*",namespaces=self.nsmap)
我得到一个下级节点列表:

[<Element {http://www.genicam.org/GenApi/Version_1_0}ToolTip at 0x1175830>, <Element {http://www.genicam.org/GenApi/Version_1_0}Description at 0x117b6c8>, <Element {http://www.genicam.org/GenApi/Version_1_0}DisplayName at 0x117bb48>, <Element {http://www.genicam.org/GenApi/Version_1_0}Visibility at 0x117bb90>, <Element {http://www.genicam.org/GenApi/Version_1_0}Streamable at 0x117bd88>, <Element {http://www.genicam.org/GenApi/Version_1_0}EnumEntry at 0x117b8c0>, <Element {http://www.genicam.org/GenApi/Version_1_0}EnumEntry at 0x1214878>, <Element {http://www.genicam.org/GenApi/Version_1_0}EnumEntry at 0x1214560>, <Element {http://www.genicam.org/GenApi/Version_1_0}pValue at 0x1214a70>]
这给了我一个空集:

[]
我还尝试在xpath中指定名称空间,这总是导致
lxml.etree.xpathevaleror:Invalid expression
错误

最后,我想在各种元素上进行此操作,例如:

self.root.xpath("descendant::*[@Name='GevCCP']/pValue")
self.root.xpath("descendant::*[@Name='GevCCP']/EnumEntry[@Name='Group']/Value")
self.root.xpath("descendant::*[@Name='GevHeartbeatTimeoutReg']/Address")
lxml文档似乎没有涵盖我的用例,我发现的关于xpath和名称空间的任何其他内容似乎都不完整。

最好的解决方案是注册一个在XML源中使用的名称空间。通常,这是通过将其指定给可以在表达式中使用的前缀来实现的。您的
nsmap
变量是否正确映射了名称空间?选择前缀(例如
g
):

然后使用前缀限定XPath选择器:

self.root.xpath("descendant::*[@Name='GevCCP']/g:ToolTip", namespaces=self.nsmap)

您有一个名称空间
http://www.genicam.org/GenApi/Version_1_0
您必须注册。如果未将命名空间映射到前缀或(如果您的api支持)作为默认名称,则无法使用元素的本地名称作为选择器(例如,
/ToolTip
pValue
)来选择元素。请尝试
“后代::*[@Name='GevCCP']/*[local-Name()='ToolTip']”
。如果可以的话,你需要注册名称空间(或者在你所有的表达式中忽略它)。一定是做错了什么,因为这是可行的。我想你必须把
namespaces=self.nsmap
作为第二个参数。
self.nsmap = {'g': 'http://www.genicam.org/GenApi/Version_1_0'}
self.root.xpath("descendant::*[@Name='GevCCP']/g:ToolTip", namespaces=self.nsmap)