XQuery简单递归查询子级到XML的顶级父级

时间:2019-04-07 21:11:48

标签: xml recursion xquery parent-child hierarchy

  

输入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>
  

您能帮我如何为每个“需求/家庭/人”获取具有现有元素“年龄”的头等亲“人”吗?

     

我的关注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)]”,但未成功。

1 个答案:

答案 0 :(得分:1)

调整where中的local:recons()子句,以确保您仅选择$parrent(元素和变量不是拼写为父元素吗?),如果它有{{1 }}和age匹配name

您可以使用谓词过滤器轻松做到这一点:

$person/mother

适用于该功能:

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