【问题标题】:Stripping all elements except one in XML using XSLT使用 XSLT 去除 XML 中除一个之外的所有元素
【发布时间】:2010-09-23 23:31:46
【问题描述】:

我想从 XML 中删除所有元素,但名为 的元素的内容除外。例如:

<root>
 <a>This will be stripped off</a>
 <source>But this not</source>
</root>

XSLT 之后:

But this not

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

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

来自 cmets

在我真正的 XML 中,我有源代码 不同命名空间中的元素。我需要 谷歌如何创建匹配 不同元素的模式 命名空间。我想把每个 提取的字符串也换行;​​-)

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    离你不远了。您没有得到任何输出的原因是您的根匹配所有模板不是递归的,而是终止的,因此您需要在其中放置一个 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>
    

    请注意,我已将输出模式更改为 textsource 模板以简单地输出节点的文本值,因为看起来您需要文本而不是 XML 输出。

    【讨论】:

    • 我忘了说明我的源元素不在根目录中。它们很深(例如在第 5 级或其他地方)。我试过 match="//source" 但没有运气:-(
    • 我不确定您所说的“无输出”是什么意思?我使用 Visual Studio XSLT 编辑器对其进行了测试,当给定源文档时,它肯​​定会产生输出“但这不是”。
    • &lt;source&gt; 元素不需要位于此样式表的根;它将遍历整个 XML 结构,直到找到它们为止。
    • 你是对的。它适用于上面的示例。在我真正的 XML 中,我在不同的命名空间中有源元素。我需要谷歌如何为不同命名空间中的元素创建匹配模式。谢谢。
    • 我想将每个提取的字符串也放入换行符;-)
    【解决方案2】:

    只是为了好玩,最好的解决方案:

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:ex="http://example.org">
        <xsl:output method="text"/>
        <xsl:template match="text()"/>
        <xsl:template match="ex:source">
            <xsl:value-of select="concat(.,'&#xA;')"/>
        </xsl:template>
    </xsl:stylesheet>
    

    有了这个输入:

    <root xmlns="http://example.org">
        <a>This will be stripped off</a>
        <source>But this not</source>
    </root>
    

    输出:

    But this not
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2015-06-18
      • 2017-07-06
      • 1970-01-01
      • 2023-01-05
      相关资源
      最近更新 更多