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

如何用XPath仅在所有子描述扩展为valid时获取描述名称?

XPath解决方案:满足“所有子节点符合指定值时取父节点属性”的需求

Let's break this down with practical examples and plain explanations—since checking "all child nodes meet a condition" can feel counterintuitive at first.

一、通用需求:所有子节点有指定值时,获取父节点属性

The core trick here is reverse validation: if there are no child nodes under the parent that don't match the specified value, then all child nodes must match it. Here's the reusable XPath template:

//parent-node[not(child-node != 'target-value')]/@desired-attribute

For example: If you have <book> nodes with multiple <chapter> children, and you want the id attribute of books where every <chapter> is marked "completed", the XPath would be:

//book[not(chapter != 'completed')]/@id

If your environment supports XPath 2.0 or later, you can use the more readable every function for explicit logic:

//book[every $chap in chapter satisfies $chap = 'completed']/@id

二、具体场景:获取符合条件的description name

First, let's assume your XML structure looks something like this (to ground the solution):

<root>
  <description name="testing1">
    <extension>valid</extension>
    <extension>invalid</extension>
  </description>
  <description name="testing2">
    <extension>valid</extension>
    <extension>valid</extension>
  </description>
  <description name="testing3">
    <extension>valid</extension>
  </description>
</root>

To get the name value "testing2" only if all its <extension> children equal "valid", here are two working approaches:

Approach 1 (XPath 1.0 compatible)

//description[@name='testing2' and not(extension != 'valid')]/@name

Breakdown:

  • @name='testing2': First lock onto the description node with your target name
  • not(extension != 'valid'): Ensure there are no <extension> children that aren't "valid" (meaning all are valid)

Approach 2 (XPath 2.0+ for readability)

//description[@name='testing2' and every $ext in extension satisfies $ext = 'valid']/@name

This uses the every function to directly state "all extension children meet the 'valid' condition", making the intent clearer.

If you want to return the text value of the attribute (instead of the attribute node itself), wrap the path in string():

string(//description[@name='testing2' and not(extension != 'valid')]/@name)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:05:54