使用 XSLT 去除 XML 中除一个元素之外的所有元素

lza*_*zap 3 xml xslt

我想从 XML 中删除除名为 <source> 的元素内容之外的所有元素。例如:

<root>
 <a>This will be stripped off</a>
 <source>But this not</source>
</root>
Run Code Online (Sandbox Code Playgroud)

XSLT 之后:

But this not
Run Code Online (Sandbox Code Playgroud)

我已经尝试过,但没有运气(没有输出):

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

 <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="source">
      <xsl:copy>
         <xsl:apply-templates select="node()"/>
      </xsl:copy>
    </xsl:template>

    <xsl:template match="@*|node()">

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

来自评论

在我的真实 XML 中,我的源元素位于不同的命名空间中。我需要谷歌如何为不同命名空间中的元素创建匹配模式。我想将每个提取的字符串也放入换行符;-)

Gre*_*ech 5

你离我们并不遥远。您没有获得任何输出的原因是因为您的根匹配所有模板不是递归的,而是只是终止,因此您需要apply-templates在其中进行调用。以下样式表给出了预期的输出。

<xsl:stylesheet version="1.0" 
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text"/>

    <xsl:template match="@*|node()">
        <xsl:apply-templates select="@*|node()"/>
    </xsl:template>

    <xsl:template match="source">
        <xsl:value-of select="text()"/>
    </xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

请注意,我已将输出模式更改为,text并将source模板更改为仅输出节点的文本值,因为看起来您需要文本而不是 XML 输出。