ai didi

python - lxml xpath 的语法问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:08 24 4
gpt4 key购买 nike

在 Python 中使用 lxml 解析 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 语法访问该列表的第一个子元素?

我试过:

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

这给了我一个空集:

[]

我也试过在 xpath 中指定命名空间,这总是会导致 lxml.etree.XPathEvalError: 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 和 namespace 的任何其他内容似乎都不完整。

最佳答案

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

self.nsmap = {'g': 'http://www.genicam.org/GenApi/Version_1_0'}

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

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

关于python - lxml xpath 的语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24564020/

24 4 0
文章推荐: python - 是否可以在 Python 中创建带状态的嵌套函数?
文章推荐: c - 在 C 中实现函数重载的最佳方法是什么?
文章推荐: javascript - HTML:在图像和视频上显示透明封面
文章推荐: mongodb - 使用enctype集在mongodb中保存数据时出现问题
太空宇宙
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com