With this XQuery expression
for $ex in distinct-values(//products/product/@group)
return $ex
and this XML
<xml>
<products>
<product id="10" group="2"></product>
<product id="20" group="1"></product>
<product id="25" group=""></product>
<product id="30" group="2"></product>
<product id="35" group=""></product>
</products>
</xml>
I'm getting only:
But I also need:
Expecting (order not of interest):
Only 1 product (the first if more than 1 with the same group) of a group and also every product with no group.
Every product with an empty group should also be returned in this xquery, but how?
Also the empty string is a distinct value and should be returned already, but likely you're simply not observing it. Changing your query to
for $ex in distinct-values(//products/product/@group)
return <value>{ $ex }</value>
you will get a result like
<value>2</value>
<value>1</value>
<value/>
(while <value/>
is equivalent to <value></value>
, and "contains" the empty string).
If you want to match both a single product for empty groups and all products without a group, you can for example split apart the query in two parts: filtering for products with groups, and then adding those without.
(
(: return first product for each product group :)
for $group in distinct-values(//products/product/@group)
(: unless group is empty :)
where $group
return (//product[@group eq $group])[1],
(: add products without any group :)
//product[@group eq '']
)
Xpath 1.0 gives an ability to find this elements without any program code
//product[
not(@group = preceding-sibling::product/@group)
or (@group="")
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.