编写XPath表达式验证所有Status元素值均为NEW
Given your sample XML:
<Accounts> <Account> <AccountNumber>12345</AccountNumber> <Status>NEW</Status> </Account> <Account> <AccountNumber>12346</AccountNumber> <Status>NEW</Status> </Account> <Account> <AccountNumber>12347</AccountNumber> <Status>NEW</Status> </Account> </Accounts>
Here are a few practical XPath expressions to confirm every <Status> element has the value NEW:
Option 1: Check for absence of non-NEW Status elements (XPath 1.0 compatible)
This expression returns true if there are no <Status> elements with a value other than NEW, which means all are valid:
boolean(not(/Accounts/Account/Status[text() != 'NEW']))
How it works:
/Accounts/Account/Status[text() != 'NEW']selects any Status element that doesn't match "NEW"not(...)negates that selection (returns true if no such elements exist)boolean(...)ensures the result is a clear boolean value (true/false)
Option 2: Compare counts of total vs valid Status elements (XPath 1.0 compatible)
This checks if the total number of <Status> elements equals the number of those with value NEW:
count(/Accounts/Account/Status) = count(/Accounts/Account/Status[text() = 'NEW'])
This is straightforward—if both counts match, every Status is "NEW".
Option 3: Explicit "every" check (XPath 2.0 and above)
If you're using an XPath 2.0+ compliant tool, this more readable expression directly asserts that every Status element satisfies the condition:
every $status in /Accounts/Account/Status satisfies $status/text() = 'NEW'
This is the most intuitive option if your environment supports XPath 2.0 or higher.
All of these will return true for your sample XML, and false if any <Status> element has a different value (like "ACTIVE" or "INACTIVE").
内容的提问来源于stack exchange,提问作者Pramod S

