使用 XSLT 从 XML 中删除空标签(空格除外)

问题描述 投票:0回答:1

我希望使用 xslt 从 xml 中删除所有空白标签,除非标签包含空格。此外,对换行符等不应有影响。xml 应按原样复制,除了没有值的空白标签或空格。

源 XML

<inRoot>
    <t1></t1>
    <t2> </t2>
    <t3>World</t3>
</inRoot>

我想要的输出

<inRoot>
    <t2> </t2>
    <t3>World</t3>
</inRoot>

我尝试的 XSLT 正在删除 t1,但给了我一个空行来代替 t1。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
 <xsl:strip-space elements=""/>
    <xsl:template match="/">
        <xsl:apply-templates select="*"/>
    </xsl:template>
    <xsl:template match="*">
            <xsl:if test=".!=''">
                <xsl:copy>
                  <xsl:copy-of select="@*"/>
                  <xsl:apply-templates/>
                </xsl:copy>
            </xsl:if>
    </xsl:template>
</xsl:stylesheet>

这段代码给我的输出为

<inRoot>
    
    <t2> </t2>
    <t3>World</t3>
</inRoot>

有人可以告诉我为什么我要为 t1 增加这条额外的线路吗?

问候

xml xslt
1个回答
0
投票

使用身份转换模板(在 XSLT 1 和 2 中)或声明(在 XSLT 3 中)

<xsl:mode on-no-match="shallow-copy"/>
加上模板

<xsl:template match="*[not(node())]"/>

确保没有任何内容的元素节点/任何子节点不会被复制。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.