这种转变:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:param name="pNum" select="0"/>
<xsl:copy>
<xsl:apply-templates select="node()[1]|@*">
<xsl:with-param name="pNum" select="$pNum"/>
</xsl:apply-templates>
</xsl:copy>
<xsl:apply-templates select="following-sibling::node()[1]">
<xsl:with-param name="pNum" select="$pNum"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="HeaderValue1">
<xsl:param name="pNum" select="0"/>
<HeaderValue1><xsl:value-of select="$pNum+1"/></HeaderValue1>
<xsl:apply-templates select="following-sibling::node()[1]">
<xsl:with-param name="pNum" select="$pNum+1"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="OrderLineItems[not(. = preceding-sibling::*[1])]">
<xsl:param name="pNum" select="0"/>
<OrderLineItems>
<xsl:apply-templates select="node()[1]|@*">
<xsl:with-param name="pNum" select="$pNum+1"/>
</xsl:apply-templates>
</OrderLineItems>
<xsl:apply-templates select="following-sibling::node()[1]">
<xsl:with-param name="pNum" select="$pNum+1"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="Item[not(. = ../preceding-sibling::*[1])]">
<xsl:param name="pNum" select="0"/>
<Item><xsl:value-of select="$pNum"/></Item>
</xsl:template>
<xsl:template match="Order">
<xsl:param name="pNum" select="0"/>
<Order>
<xsl:apply-templates select="node()[1]|@*">
<xsl:with-param name="pNum" select="$pNum"/>
</xsl:apply-templates>
<xsl:apply-templates select="following-sibling::node()[1]">
<xsl:with-param name="pNum" select=
"$pNum +1 + count(OrderLineItems[not(. = preceding-sibling::*[1])])"/>
</xsl:apply-templates>
</Order>
</xsl:template>
</xsl:stylesheet>
当应用于提供的 XML 文档时(更正为格式正确):
<t>
<Order>
<HeaderValue1>ORDER1</HeaderValue1>
<OrderLineItems>
<Item>A</Item>
</OrderLineItems>
<OrderLineItems>
<Item>A</Item>
</OrderLineItems>
<OrderLineItems>
<Item>A</Item>
</OrderLineItems>
<OrderLineItems>
<Item>B</Item>
</OrderLineItems>
</Order>
<Order>
<HeaderValue1>ORDER2</HeaderValue1>
<OrderLineItems>
<Item>B</Item>
</OrderLineItems>
</Order>
</t>
产生想要的正确结果:
<t>
<Order>
<HeaderValue1>1</HeaderValue1>
<OrderLineItems>
<Item>2</Item>
</OrderLineItems>
<OrderLineItems>
<Item>A</Item>
</OrderLineItems>
<OrderLineItems>
<Item>A</Item>
</OrderLineItems>
<OrderLineItems>
<Item>3</Item>
</OrderLineItems>
<Order>
<HeaderValue1>4</HeaderValue1>
<OrderLineItems>
<Item>5</Item>
</OrderLineItems>
</Order>
</Order>
</t>