跳转到内容

XQuery/限制子树

来自维基教科书,开放书籍,开放世界

您有一个数据树,并且您希望将结果限制在树的给定级别。

示例数据

[编辑 | 编辑源代码]

假设我们有一个组织结构图,其结构如下

<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 title="CIO" name="Tracy Technie"/>
</position>
</source >

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.

<syntaxhighlight lang="xml">
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()}
 }
华夏公益教科书