XQuery/Limiting Child Trees
Motivation
You have a tree of data and you want to limit the results to a given level of a tree.
Sample Data
Assume we have an org chart that has the following structure:
<position title="President" name="Peg Prez"> <position title="Vice President" name="Vic Vicepres"> <position title="Director" name="Dan Director"> <position title="Manager" name="Marge Manager"> <position title="Supervisor" name="Sue Supervisor"> <position title="Project Manager" name="Pete Project"/> </position> </position> </position> </position> <position title="CFO" name="Barb Beancounter"/> </position> <position title="CIO" name="Tracy Technie"/> </position> </position>
To display an org chart you only want to display the individual and their direct reports.
Approach
We will use computed element and attribute constructors. let $positions := doc('/db/my-org/apps/hr/data/positions.xml')/position
{for $subelement in $positions/position
return
element {name($subelement)}
{for $attribute in $subelement/@*
return attribute {name($attribute)} {$attribute}
,
$subelement/text()}
}