How do I make negative join ("except") in XPath?
I have this XML:
<Products xmlns="urn:shop.fruit">
<!-- documento XML para a pergunta 5 -->
<Stock>
<product name="banana" quant="2000" un="kg"/>
<product name="aple" quant="3000" un="kg"/>
<product name="orange" quant="3500" un="kg"/>
<product name="melon" quant="1000" un="kg"/>
</Stock>
<Prices>
<product name="aple" un="€">1.2</produto>
<product name="melon" un="€">1.5</produto>
</Prices>
</Products >
I want XPath to give me as a result the names of all products that are in the stock tag, except for those in the Prices tag. As a result, I want: name = "banana"; name = "orange". I tried this XPath: /Produtos/Stock/produto/@nome except /Produtos/Preços/produto/@nome
but it looks like the exception operator is not accepted. Any suggestions?
source to share
The operator except
is only available in XPath 2.0, but you can do what you want in XPath 1.0 (and XPath 2.0) without except
...
First, in the context of the environment in which the XPath will be evaluated, define the namespace prefix for the namespace urn:shop.fruit
:
u=urn:shop.fruit
Then the next XPath
/u:Products/u:Stock/u:product[not(@name = /u:Products/u:Prices/u:product/@name)]/@name
Will return
banana
orange
upon request.
Update:
Here is a concise solution suggested by @Tomalak:
/u:Products/u:Stock/u:product/@name[not(. = /u:Products/u:Prices/u:product/@name)]
@Tomalak and @JLRishe also offered a helpful explanation that these solutions work because in XPath it X = Y
is a given operation that works like an INNER JOIN. @ JL Notes in more detail which is X != Y
also a set operation, but not specifically equivalent not(X = Y)
.
source to share