XQuery - 去除标签但保留文本

4

我可以如何在XQuery中去除一组标签,但仍然保留其文本?例如,如果我有:

<root>
    <childnode>This is <unwantedtag>some text</unwantedtag> that I need.</childnode>
</root>

我该如何去除不需要的标签以获得:

我该如何去除不需要的标签以获得:

<root>
    <childnode>This is some text that I need.</childnode>
</root>

实际上,我真正想得到的只是文本,例如:

This is some text that I need.

当我执行以下操作时:
let $text := /root/childnode/text()

I get:

This is  that I need.

它缺少其中的一些文本部分。

有什么想法可以返回这是我需要的一些文本。

谢谢。


好问题,+1。请看我的答案,其中包含完整、最简单和最短的解决方案。 :) - Dimitre Novatchev
3个回答

5

您是否对子节点的字符串值感兴趣(而不是文本节点序列或简化元素)?您可以使用fn:string获取字符串值:

string(/root/childnode)

2

使用:

/*/childnode//text()

当对提供的XML文档评估此XQuery时:
<root>
 <childnode>This is <unwantedtag>some text</unwantedtag> that I need.</childnode>
</root>

期望得到的正确结果已经生成:
This is some text that I need.

0

这个 XQuery:

declare function local:copy($element as element()) {
   element {node-name($element)}
           {$element/@*,
            for $child in $element/node()
            return if ($child instance of element())
                   then local:match($child)
                   else $child
           }
};
declare function local:match($element as element()) {
   if ($element/self::unwantedtag)
   then for $child in $element/node()
        return if ($child instance of element())
               then local:match($child)
               else $child
   else local:copy($element)
};
local:copy(/*)

输出:

<root>
    <childnode>This is some text that I need.</childnode>
</root>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接