通过子元素条件获取父元素Id的XPath编写求助
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, andcontainscan’t check for "B or C" in that format. For exact matches of specific values, we don’t needcontainshere 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 withId="G"and text exactly equal to either "B" or "C" (swaptext()withcontains()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 withId="S"and text exactly equal to "F"./@Id: Finally, extracts theIdattribute 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

