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

通过子元素条件获取父元素Id的XPath编写求助

Fixing Your XPath to Target the Correct H Elements

Let's work through fixing your XPath step by step to get the exact H element IDs you need. First, let's address the issues in your initial attempt, then build the correct query tailored to your requirements.

Issues in Your Original XPath

Your first try //H/M/A[@Id='G'][contains(text(),'B C']/../../@Id has two critical problems:

  • Syntax error in the contains() function: You’re missing a closing parenthesis, and contains can’t check for "B or C" in that format. For exact matches of specific values, we don’t need contains here anyway.
  • You didn’t include the required condition for the A[@Id='S' and text()='F'] element, which is a key part of your filter.

Correct XPath Query

To find all H elements where at least one child M contains both required A elements, use this XPath:

//H[M[A[@Id='G' and (text()='B' or text()='C')] and A[@Id='S' and text()='F']]]/@Id

Breakdown of the Query

Let’s walk through each part to make it clear:

  • //H: Starts by selecting all H elements in the document.
  • [M[...]]: Filters H elements to only those that have an M child matching the inner conditions.
  • A[@Id='G' and (text()='B' or text()='C')]: Ensures the M has an A element with Id="G" and text exactly equal to either "B" or "C" (swap text() with contains() if you need partial matches, but exact match is better for your requirements).
  • and A[@Id='S' and text()='F']: Adds the rule that the same M element must also have an A element with Id="S" and text exactly equal to "F".
  • /@Id: Finally, extracts the Id attribute from the filtered H elements.

Testing with Your Sample XML

In your provided XML, this XPath will return 4326789—the only H element that meets all your criteria, since it has an M element (Ind="aa") with both A[@Id='G' and text()='B'] and A[@Id='S' and text()='F'].

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:00:13