【问题标题】:XSLT Copy all Nodes except 1 elementXSLT 复制除 1 个元素之外的所有节点
【发布时间】:2013-02-20 16:38:25
【问题描述】:
<events>
    <main>
        <action>modification</action>
        <subAction>weights</subAction>
    </main>
</events>
<SeriesSet>
    <Series id="Price_0">
        <seriesBodies>
            <SeriesBody>
                <DataSeriesBodyType>Do Not Copy</DataSeriesBodyType>
            </SeriesBody>
        </SeriesBodies>
    </Series>
</SeriesSet>

如何复制所有 xml 并排除 DataSeriesBodyType 元素

【问题讨论】:

标签: xml xslt


【解决方案1】:

您只需使用身份模板(就像您之前使用的那样),然后使用与 DataSeriesBodyType 匹配的模板,它什么都不做。

代码是:

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


    <xsl:output method="xml" encoding="utf-8" indent="yes"/>

    <!-- Identity template : copy all text nodes, elements and attributes -->   
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <!-- When matching DataSeriesBodyType: do nothing -->
    <xsl:template match="DataSeriesBodyType" />

</xsl:stylesheet>

如果要规范化输出以删除空数据文本节点,则将以下模板添加到上一个样式表中:

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

【讨论】:

  • 我已经尝试过了,但它返回的元素没有值。我根本不想显示元素。
  • 您发布的 XML 不是完整的 XML,并且其中有一些错误(例如带有结束标签 SeriesBody 的 seriesBody),因此我使用您的 XML 的更正版本检查了我的代码(可能不一样)。如果 match="DataSeriesBodyType" 完全匹配(包括大写和小写字母),请检查名称,如果它不起作用,请发布您的完整 XML。
  • 您要排除哪个元素 DataSeriesBodyType 或 SeriesBodyType?只需将 上的 match 属性值替换为要排除的 XML 元素名称即可。
【解决方案2】:

以下内容对我有用,因为有时我需要创建一个没有一个元素的树来创建一个变量,有时我需要删除另一个元素来创建另一个变量。请注意,主匹配不应匹配根元素“/”,因为如果这样做,它只会在仅处理一个根元素时复制整个三个。但请记住,我们为所有节点使用应用模板的这种解决方案会干扰您可能需要执行其他工作的其他模板,因此您需要使用“模式”选项来分隔它们。

    <xsl:template match="node()|@*">
       <xsl:copy>
         <xsl:apply-templates select="node()[not(self::DataSeriesBodyType)]|@*"/>
       </xsl:copy>
    </xsl:template>

【讨论】:

  • 不是一个非常有效的解决方案。最好保留身份转换模板原样,并添加一个与您要删除的元素的父元素匹配的模板,以执行上述操作。
  • 请给我看看好吗。
  • 谢谢迈克尔。那太棒了。会张贴自己,因为那是您的解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 2018-12-30
  • 2013-08-02
  • 2020-12-17
  • 2020-08-23
  • 1970-01-01
相关资源
最近更新 更多