You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python(lxml)中用XPath获取指定兄弟节点的子节点值?

解决lxml XPath获取指定XML节点值的问题

咱们先梳理下你的核心需求:定位到包含Known.Node[@KnownAttribute='123']的目标Some.Node,然后获取该节点下Relevant.Node中,对应Name为Known.Name的Property节点的Value文本。

你的原XPath查询失败,问题出在/..//Property这部分:/..确实能拿到Known.Node的父节点(也就是目标Some.Node),但后面的//Property是模糊匹配该节点下所有层级的Property,可能因为XML结构的层级关系或lxml的解析细节,导致匹配不到正确的节点。更稳妥的方式是指定从Some.Node到Relevant.Node的明确路径,避免无差别遍历。

正确的XPath写法

把查询语句改成以下两种方式之一即可:

方式1:用父节点相对路径(简洁版)

attribute_value = "123"
query = "//Known.Node[@KnownAttribute='%s']/../Relevant.Node/Property[Name='Known.Name']/Value" % attribute_value

方式2:用parent::轴(可读性更强)

如果想更清晰地表达“父节点”逻辑,可以用XPath的轴语法:

query = "//Known.Node[@KnownAttribute='%s']/parent::*/Relevant.Node/Property[Name='Known.Name']/Value" % attribute_value

完整可验证代码

下面是整合后的测试代码,直接运行就能得到预期结果:

from lxml import etree

# 模拟你的XML结构(方便本地测试)
xml_content = """
<Example>
  <Path>
    <Some.Node>
      <Some.Node>
        <Known.Node KnownAttribute="123"/>
        <Some.Stuff>
          <Nothing.Important>Bla</Nothing.Important>
        </Some.Stuff>
        <Relevant.Node>
          <Property>
            <Name>Some</Name>
            <Value>True</Value>
          </Property>
          <Property>
            <Name>Known.Name</Name>
            <Value>Desired Value</Value>
          </Property>
          <Property>
            <Name>Some.Other</Name>
            <Value>Yes</Value>
          </Property>
        </Relevant.Node>
      </Some.Node>
      <Some.Node>
        <!-- 其他无关节点 -->
      </Some.Node>
    </Some.Node>
  </Path>
</Example>
"""

# 解析XML并执行查询
root = etree.fromstring(xml_content)
attribute_value = "123"
query = "//Known.Node[@KnownAttribute='%s']/../Relevant.Node/Property[Name='Known.Name']/Value" % attribute_value

result = root.xpath(query)
if result:
    print(result[0].text)  # 输出:Desired Value
else:
    print("未找到匹配的节点")

补充说明

如果你的实际XML存在命名空间,需要在XPath中指定命名空间前缀(比如root.xpath(query, namespaces={"ns": "http://your-namespace-url"})),但从你给出的结构来看,暂时不需要考虑这个因素。

内容的提问来源于stack exchange,提问作者NPS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:18:02