这种转变:
<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:key name="kRowById"
match="ROW[not(@TYPE='TOTAL' or @TYPE='MAIN')]"
use="@ID"/>
<xsl:template match="ROW[@TYPE='TOTAL' or @TYPE='MAIN']">
<xsl:copy-of select="."/>
<xsl:copy-of select="key('kRowById', @ID)"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
当应用于 XML 文档时(从提供的 XML 片段生成,通过将其包装到单个顶部元素中):
<t>
<ROW TYPE="SPECIFICATION" ID="1">
<R1>English1</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="1">
<R1>Maths1</R1>
</ROW>
<ROW TYPE="TOTAL" ID="1">
<R1>Code1</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="2">
<R1>English2</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="2">
<R1>Maths2</R1>
</ROW>
<ROW TYPE="TOTAL" ID="2">
<R1>Code2</R1>
</ROW>
<ROW TYPE="MAIN" ID="3">
<R1>Code3</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="4">
<R1>English4</R1>
</ROW>
<ROW TYPE="TOTAL" ID="4">
<R1>Code4</R1>
</ROW>
</t>
产生想要的正确结果:
<ROW TYPE="TOTAL" ID="1">
<R1>Code1</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="1">
<R1>English1</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="1">
<R1>Maths1</R1>
</ROW>
<ROW TYPE="TOTAL" ID="2">
<R1>Code2</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="2">
<R1>English2</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="2">
<R1>Maths2</R1>
</ROW>
<ROW TYPE="MAIN" ID="3">
<R1>Code3</R1>
</ROW>
<ROW TYPE="TOTAL" ID="4">
<R1>Code4</R1>
</ROW>
<ROW TYPE="SPECIFICATION" ID="4">
<R1>English4</R1>
</ROW>
更新:
根据 OP 在评论中的要求,如果必须将任何不同于“SPECIFICATION”的值放在组的开头,请使用以下代码:
<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:key name="kRowById"
match="ROW[not(@TYPE='TOTAL' or @TYPE='MAIN')]"
use="@ID"/>
<xsl:template match="ROW[not(@TYPE='SPECIFICATION')]">
<xsl:copy-of select="."/>
<xsl:copy-of select="key('kRowById', @ID)"/>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>