输入XML

<req>
  <family>
    <person>
      <id>id1</id>
      <name>name1</name>
      <mother>mother1</mother>
      <age>age1</age>
    </person>
    <person>
      <id>id2</id>
      <name>name2</name>
      <mother>mother2</mother>
      <age>age2</age>
    </person>
    <person>
      <id>id4</id>
      <name>mother3</name>
      <mother>mother4</mother>
    </person>
    <person>
      <id>id3</id>
      <name>mother2</name>
      <mother>mother3</mother>
      <age>age3</age>
    </person>
  </family>
</req>

你能帮我如何为每个“需求/家庭/个人”获取具有现有元素“年龄”的顶级parrent“person”吗?
我的follow xquery
declare function local:recons($family as element(*), $person as element(*))
    as element(*) {
    let $parrent := for $p in $family/person
    where $p/name=$person/mother
    return local:recons($family,$p)
    return
    <person>
    {$person/*}
    <parrent>{$parrent}</parrent>
    </person>
};

declare function xf:MyTest($inputXML as element(*))
    as element(*) {
       <res>
       <family>
       {
       for $person in $inputXML/family/person
       return local:recons($inputXML/family,$person)
       }
       </family>
       </res>
};

declare variable $inputXML as element(*) external;

xf:MyTest($inputXML)

预期结果
<res>
  <family>
    ...
    <person>
      <id>id2</id>
      <name>name2</name>
      <mother>mother2</mother>
      <age>age2</age>
      <parrent>
        <person>
          <id>id3</id>
          <name>mother2</name>
          <mother>mother3</mother>
          <age>age3</age>
          <parrent/>
        </person>
      </parrent>
    </person>
    ...
  </family>
</res>

实际结果
<res>
  <family>
    ...
    <person>
      <id>id2</id>
      <name>name2</name>
      <mother>mother2</mother>
      <age>age2</age>
      <parrent>
        <person>
          <id>id3</id>
          <name>mother2</name>
          <mother>mother3</mother>
          <age>age3</age>
          <parrent>
            <person>
              <id>id4</id>
              <name>mother3</name>
              <mother>mother4</mother>
              <parrent/>
            </person>
          </parrent>
        </person>
      </parrent>
    </person>
    ...
  </family>
</res>

我尝试使用祖先和xpath,比如'$parrent//person[fn:exists(age)]',失败。
我尝试使用祖先和xpath,比如'$parrent//person[fn:exists(age)]',失败。

最佳答案

调整where子句以确保您只选择local:recons()(该元素和变量不应该拼写为父元素吗?)如果它有一个$parrent并且age匹配name
使用谓词过滤器可以很容易地做到这一点:

where $p[age]/name = $person/mother

应用于函数:
declare function local:recons($family as element(*), $person as element(*))
    as element(*) {
    let $parrent := for $p in $family/person
      where $p[age]/name = $person/mother
      return local:recons($family,$p)
    return
      <person>
        {$person/*}
        <parrent>{$parrent}</parrent>
      </person>
};

09-26 15:47