【问题标题】:preserve whitespace between xsl:sort'd nodes保留 xsl:sort'd 节点之间的空白
【发布时间】:2010-10-06 23:33:39
【问题描述】:

我试图弄清楚如何在我正在排序的节点之间保留空白节点。这是一个例子。

输入:

<a>
    <b>
        <c>
            <d>world</d>
        </c>
        <c>
            <d>hello</d>
        </c>
    </b>
    <e>some other stuff</e>
</a>

期望的输出:

<a>
    <b>
        <c>
            <d>hello</d>
        </c>
        <c>
            <d>world</d>
        </c>
    </b>
    <e>some other stuff</e>
</a>

这是我的 xslt:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

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

    <xsl:template match="a/b">
        <xsl:copy>
            <xsl:apply-templates select="c">
                <xsl:sort select="d"/>
            </xsl:apply-templates>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

当我通过 xsltproc 运行它时,我得到了这个:

<a>
    <b><c>
            <d>hello</d>
        </c><c>
            <d>world</d>
        </c></b>
    <e>some other stuff</e>
</a>

我宁愿以后不要把它整理好。想法?

【问题讨论】:

    标签: xslt sorting


    【解决方案1】:

    您需要将这两行添加到样式表的顶部:

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>
    

    第一行去除文档中的所有空白,第二行缩进输出。

    【讨论】:

      【解决方案2】:

      您的第二个模板匹配所有 b,但仅在 c 元素上应用模板。包含的文本节点被丢弃。这就是为什么您在输出中看不到 b 和 c 元素之间的空格。

      您必须重新格式化树,因为重新排序后的文本节点看起来不漂亮(即使您设法包含它们)。安德鲁斯解决方案将做到这一点。

      【讨论】: