如何使用XPath3表达式从含多元素的XML标签中获取特定元素
success="N" Attribute Got it, let's fix that XPath expression for you. Your current approach has a syntax error in how you're targeting the attribute, and we can simplify this to directly select the elements you need.
First, let's break down the issue with your existing code:
- The expression
.//*:@successuses invalid XPath syntax. To target attributes, you need to use the@prefix before the attribute name, and wrap the condition in a predicate ([]).
The Correct XPath
To select all elements anywhere in your XML that have a success attribute with the exact value "N", use this XPath:
.//*[@success='N']
Let's break this down:
.//*: Selects all descendant elements starting from the current context node (so it searches the entire XML tree under your payload).[@success='N']: Filters those elements to only include ones where thesuccessattribute equals"N".
Using with the xpath3 Function
Depending on what you need to do, adjust the third parameter of the xpath3 function:
To get the matching elements as a nodeset:
#[xpath3('.//*[@success="N"]', payload, "NODESET")]This will return all elements that meet the condition, which you can then process further.
To check if any such element exists (return a boolean):
#[xpath3('exists(.//*[@success="N"])', payload, "BOOLEAN")]This will return
trueif there's at least one element withsuccess="N", otherwisefalse.To get a specific attribute or value from the matching elements:
If you wanted to, say, get thetypeattribute of the matching elements, you could use:#[xpath3('.//*[@success="N"]/@type', payload, "STRING")]This would return the
typeattribute value (like"RETURN"from your sample XML) as a string.
Example with Your Sample XML
If your payload is:
<REQUEST type="RETURN" success="N"/>
The XPath .//*[@success='N'] will select the entire <REQUEST> element, which is exactly what you're looking for.
内容的提问来源于stack exchange,提问作者Devdas Sandbhor

