How to check via XPATH if element exist in all parent's elements
10,679
Solution 1
XPath 2.0 has 'every' for that:
every $order in /STICKERINFO/ORDER satisfies boolean($order/STICKER/ARTICLE)
And in XPath 1 you can test if there is an article for every order, i.e. if the count of orders is the same as the count of orders with articles:
count(/STICKERINFO/ORDER) = count(/STICKERINFO/ORDER[STICKER/ARTICLE])
Solution 2
This XPath 1.0 (and also XPath 2.0) expression:
boolean(/STICKERINFO/ORDER[not(STICKER/ARTICLE)])
produces true()
when there is at least one /STICKERINFO/ORDER
element that doesnt have a STICKER/ARTICLE
descendant.
Therefore, (one of) the XPath expression(s) you are after is:
not(/STICKERINFO/ORDER[not(STICKER/ARTICLE)])
Explanation:
This is a simple application of the Double Negation Law. :)
Author by
VextoR
Updated on November 22, 2022Comments
-
VextoR over 1 year
If we have an XML document:
<?xml version="1.0" encoding="utf-8"?> <STICKERINFO> <ORDER> <NUMBER>0171467783</NUMBER> <STICKER> <ARTICLE>03359140001</ARTICLE> </STICKER> <STICKER> <ARTICLE>11408038001</ARTICLE> </STICKER> </ORDER> <ORDER> <NUMBER>0171473000</NUMBER> </ORDER> </STICKERINFO>
I can check that
/STICKERINFO/ORDER/STICKER/ARTICLE
exists:boolean(/STICKERINFO/ORDER/STICKER/ARTICLE)
But how can I check if /STICKERINFO/ORDER/STICKER/ARTICLE exists in all
/STICKERINFO/ORDER/
?In current example XPATH expression should return
false
-
Dimitre Novatchev over 11 yearsVextoR, Are you aware of the fact that you have accepted an answer with XPath expressions that are twice as long as other XPath expressions producing the wanted truth value? And whose XPath 1.0 expression is significantly less efficient than another possible expression?
-
-
Kangkan over 11 yearsGood one! I was trying to write the XPath1 query!
-
VextoR over 11 yearsThanks! Can you please explain how XPATh 1 solution works? I can't understand this: ORDER[STICKER/ARTICLE]
-
BeniBela over 11 yearsORDER[..] returns only the orders for which the condition '..', is true, STICKER/ARTICLE returns all articles of the current order, and a list of nodes is true, iff there are any nodes, and false, iff there are none .
-
Dimitre Novatchev over 11 yearsUsing
count()
is in most cases less efficient than using double negation.