【问题标题】:Clear all text elements in XSL清除 XSL 中的所有文本元素
【发布时间】:2017-12-16 03:28:34
【问题描述】:

有人对此有解决方案。 我有一个完全填充了测试数据的 XML。我需要清除所有元素文本。

<xml>
    <parent>
        <child>A</child>
        <child>B</child>
        <pet>
            <dog>C</dog>
            <cat>D</cat>
        </pet>
    </parent>
</xml>

需要成为

<xml>
    <parent>
        <child></child>
        <child></child>
        <pet>
            <dog></dog>
            <cat></cat>
        </pet>
    </parent>
</xml>

我的真实 XML 包含 100 多个不同的元素名称,所以我需要一个通用的方法。

我正在尝试身份转换的变体,但出现 XSL 错误。

文件错误:cleanxml.xsl -2147467259 要创建“ELEMENT”类型的节点,必须指定一个有效的名称。

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match='/|@*|node()'>
    <!--
    Regular Identity Transform
    <xsl:copy>
        <xsl:apply-templates select='@*|node()'/>
    </xsl:copy>
    -->
    <xsl:variable name='name' select='local-name()'/>

    <xsl:element name='{$name}'>
        <xsl:apply-templates select='@*|node()'/>
    </xsl:element>

</xsl:template>

</xsl:stylesheet>

【问题讨论】:

  • 失败消息的原因是您的模板匹配了文档节点和文本节点等没有名称的节点;所以 $name 的值是一个零长度的字符串,你不能创建一个名字是零长度的字符串的元素。

标签: xml xslt


【解决方案1】:

使用这个 xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

<xsl:template match="*">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>

<xsl:template match="text()" />

</xsl:stylesheet>

【讨论】:

    【解决方案2】:

    你需要先从身份转换开始,然后添加

      <xsl:template match="text()[normalize-space()]"/>
    

    因此,使用 XSLT 3 (http://xsltfiddle.liberty-development.net/gWcDMec) 您只需要

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="3.0">
    
      <xsl:mode on-no-match="shallow-copy"/>
    
      <xsl:template match="text()[normalize-space()]"/>
    
    </xsl:stylesheet>
    

    或者对于早期版本,您需要将身份转换拼写为

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

    而不是使用xsl:mode。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 1970-01-01
      • 2015-11-30
      • 2015-09-16
      • 1970-01-01
      • 2017-07-11
      相关资源
      最近更新 更多