使用XSLT递归删除空的xml元素

Jam*_*s H 2 xml xslt recursion

我试图以递归方式从xml中删除"空"元素(没有子元素,没有属性或空属性).这是我的XSLT

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

<xsl:template match="*[not(*) and
                       string-length(.)=0 and
                       (not(@*) or @*[string-length(.)=0])]">
    <xsl:apply-templates/>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

这是输入XML.我希望这个XML转换为空字符串

<world>
    <country>
        <state>
            <city>
                <suburb1></suburb1>
                <suburb2></suburb2>
            </city>
        </state>
    </country>
</world>
Run Code Online (Sandbox Code Playgroud)

但相反,我得到了

<world>
    <country>
        <state/>
    </country>
</world>
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?我在论坛上研究了很多线程,但仍然没有运气.

mic*_*57k 6

not(*)对于任何有孩子的元素,条件都是假的 - 无论孩子包含什么.

如果你想"修剪"任何不带"水果"的树枝,请尝试:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="*[descendant::text() or descendant-or-self::*/@*[string()]]">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="@*[string()]">
    <xsl:copy/>
</xsl:template>

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