在xslt 1.0中对xml节点进行分组

时间:2012-09-10 15:06:38

标签: xml xslt xslt-1.0

输入:

输入XML

<Root>
    <Number>1</Number>
    <Reference>100</Reference>

    <Number>2</Number>
    <Reference>101</Reference>

    <Number>3</Number>
    <Reference>100</Reference>

    <Number>4</Number>
    <Reference>102</Reference>

    <Number>5</Number>
    <Reference>100</Reference>
</Root>

预期产出:

<Root>
    <Number>1</Number>
    <Reference>100</Reference>
    <RefNumber>1</RefNumber>

    <Number>2</Number>
    <Reference>101</Reference>
    <RefNumber>1</RefNumber>

    <Number>3</Number>
    <Reference>100</Reference>
    <RefNumber>2</RefNumber>

    <Number>4</Number>
    <Reference>102</Reference>
    <RefNumber>1</RefNumber>

    <Number>5</Number>
    <Reference>100</Reference>
    <RefNumber>3</RefNumber>
</Root>

如何根据Root / Reference进行分组,并在xslt 1.0的输出中为RefNumber添加序号?

先谢谢

1 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是使用 xsl:number 。每当您匹配参考元素时,请复制该元素,并添加一个 RefNumber 元素,其中Reference元素的数量具有相同的值:

<xsl:template match="Reference">
    <xsl:copy-of select="." />
    <xsl:variable name="Ref" select="." />
    <RefNumber><xsl:number count="Reference[. = $Ref]" /></RefNumber>
</xsl:template>

这是完整的XSLT

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

    <xsl:template match="Reference">
        <xsl:copy-of select="." />
        <xsl:variable name="Ref" select="." />
        <RefNumber><xsl:number count="Reference[. = $Ref]" /></RefNumber>
    </xsl:template>

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

当应用于您的示例XML时,输出以下内容:

<Root>
    <Number>1</Number>
    <Reference>100</Reference>
    <RefNumber>1</RefNumber>

    <Number>2</Number>
    <Reference>101</Reference>
    <RefNumber>1</RefNumber>

    <Number>3</Number>
    <Reference>100</Reference>
    <RefNumber>2</RefNumber>

    <Number>4</Number>
    <Reference>102</Reference>
    <RefNumber>1</RefNumber>

    <Number>5</Number>
    <Reference>100</Reference>
    <RefNumber>3</RefNumber>
</Root>

请注意使用身份转换模板复制其他现有节点。