xslt 1.0中xml节点的分组



输入:

输入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>

如何在xslt 1.0中基于根/引用进行分组并将序号添加到输出中的RefNumber?

提前感谢

实现这一点的一种方法是使用xsl:number。每当您匹配Reference元素时,复制该元素,并添加一个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>

请注意使用标识转换模板来复制其他现有节点。

相关内容

  • 没有找到相关文章

最新更新