繁体   English   中英

根据XQuery中的字符串动态重写MarkLogic xml文档

[英]Rewrite MarkLogic xml document dynamically based on strings in XQuery

我需要一个XQuery函数,该函数能够根据指定要检索的节点名称的字符串数组来重写文档,特别是返回子节点的子集。 如果要满足如下定义并需要使用任何任意文件。

local:apply-node-includes($document, $includedNodeNames as xs:string*)

鉴于我有一些xml文档

let $doc := 
  <foo a="b">
    <bar>hello</bar>
    <baz>1</baz>
    <bang>
      <text>world</text>
    </bang>
  </foo>')

然后,该函数应转换文档,以便仅返回在$ includedNodes中指定名称的子节点。

示例local:apply-node-includes($doc, 'baz')将返回

<foo a="b">
  <baz>1</baz>
</foo>

示例local:apply-node-includes($doc, ('bar','bang')))将返回

<foo a="b">
  <bar>hello</bar>
  <bang>
    <text>world</text>
  </bang>
</foo>

我尝试在节点上进行迭代,和/或使用某种形式的递归类型切换,但到目前为止仍无法正确实现。 如果它能完全递归地工作,那真是太酷了,所以“ bang.text”将仅包括孙子文本节点,而不包括它们的任何同级节点,但这可能要求太多!

我不确定这是否是最优雅的解决方案,但似乎可以满足您的要求。 这里的函数将重新创建所传递文档的根元素,然后包括所有直接子元素(及其所有属性和子元素),这些子元素的元素名称与所传递列表中的任何字符串均匹配。

declare function local:apply-node-includes( $doc as item(), $includedNodeNames as xs:string*) as item()
{
   (: Recreate the root element :)
   element {name($doc)} 
   { (: Replicate root element's attributes :)
     (for    $attribute in $doc/@* return $attribute),
     (: Replicate root element's immediate children having any of given names :)
     (for    $element in $doc/* where name($element) = $includedNodeNames 
      return $element)
   }
};

let $doc := 
  <foo a="b">
    <bar>hello</bar>
    <baz>1</baz>
    <bang>
      <text>world</text>
    </bang>
  </foo>
return local:apply-node-includes($doc, ('bar','bang'))

输出:

<foo a="b"><bar>hello</bar><bang><text>world</text></bang></foo>

@DavidDeneberg给出了一个很好的答案,但我设法使用一些xpath进一步简化了它,因此为其他人发布。

declare function local:apply-node-includes($doc as element(), $includedNodeNames as xs:string*) as element()?
{
  element {node-name($doc) }
  {
    $doc/@*,
    $doc/*[name(.)=$include-names]
  }
};

另外,这本书在主题https://en.wikibooks.org/wiki/XQuery/Filtering_Nodes上非常有用,并演示了您需要能够处理该问题的子孙部分的递归身份转换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM