I use this xpath expression to list all “NON TEST” items:
/Items/Item[State!='TEST']/Name
Normally input XML looks like this and everything works fine:
<Items>
<Item>
<Name>Item1</Name>
<State>ACTIVE</State>
</Item>
<Item>
<Name>Item2</Name>
<State>TEST</State>
</Item>
</Items>
But when Item miss State element the xpath expression selects nothing:
<Items>
<Item>
<Name>Item1</Name>
</Item>
<Item>
<Name>Item2</Name>
</Item>
</Items>
Please, how should I change my xpath expression so that it also works when State element does not exists? If State element does not exists Item is considered as “NON TEST” item. I have no option to change xml structure.
Use the following expression:
The difference is that
State!='TEST'selects those items having anyStateelement whose string value is not equal toTEST, whilenot(State='TEST')selects all items not having aStateelement whose string value is equal toTEST(whetherStateexists or not). It’s a subtle but significant difference.From the spec:
Furthermore, imagine the following input:
This expression:
…will select the first
Item‘sNameelement, because it contains at least oneStateelement not having a value ofTEST.However, this expression:
…selects no items. This second form is very often what you want.
See this note from the spec: