When using XPath or XQuery, is there a way to limit the depth of the result?
I am using BaseX, which supports XQuery 3.1 and XSLT 2.0.
For example, given this input document:
<country name="United States">
<state name="California">
<county name="Alameda" >
<city name="Alameda" />
<city name="Oakland" />
<city name="Piedmont" />
</county>
<county name="Los Angeles">
<city name="Los Angeles" />
<city name="Malibu" />
<city name="Burbank" />
</county>
<county name="Marin">
<city name="Fairfax" />
<city name="Larkspur" />
<city name="Ross" />
</county>
<county name="Sacramento">
<city name="Folsom" />
<city name="Elk Grove" />
<city name="Sacramento" />
</county>
</state>
</country>
If I execute this query: /country/state
, I get the following result:
<state name="California">
<county name="Alameda">
<city name="Alameda"/>
<city name="Oakland"/>
<city name="Piedmont"/>
</county>
<county name="Los Angeles">
<city name="Los Angeles"/>
<city name="Malibu"/>
<city name="Burbank"/>
</county>
<county name="Marin">
<city name="Fairfax"/>
<city name="Larkspur"/>
<city name="Ross"/>
</county>
<county name="Sacramento">
<city name="Folsom"/>
<city name="Elk Grove"/>
<city name="Sacramento"/>
</county>
</state>
I would like to limit the depth of the result. Ideally, there'd be a way for me to specify the depth, rather than hard-coding an XPath query.
As an example, I would like to limit the result to the result nodes and its children, but not including the grandchildren, so the result would be:
<state name="California">
<county name="Alameda" />
<county name="Los Angeles" />
<county name="Marin" />
<county name="Sacramento" />
</state>
One easy and straightforward way is to use XSLT-2.0 with an empty template cancelling all children of
<county>
. The<xsl:strip-space>
removes the space that would have been used by the children.Output is:
With XQuery, a solution could look like this:
The output is the same.