问题
I need to transform a document like this:
<root>
<products>
<ProductInfo>
<ProductID>0</ProductID>
<ProductName>Hello world!</ProductName>
</ProductInfo>
<M>
<ModelInfo>
<ModelID>0</ModelID>
<ModelName>Hello world!</ModelName>
</ModelInfo>
</M>
</products>
</root>
Into this:
<root>
<products>
<M>
<ModelInfo>
<ModelName>Hello world!</ModelName>
<ModelID>0</ModelID>
</ModelInfo>
</M>
<ProductInfo>
<ProductName>Hello world!</ProductName>
<ProductID>0</ProductID>
</ProductInfo>
</products>
</root>
So all the tags in the output should be in reversed order.
I need this for testing: I need to ensure that some external application accepts the tags in any order; and also I need it to test that my XML Schema allows tags in any order.
回答1:
Not reverse the tree, but reverse the order of sibling branches (at all levels):
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="node()">
<xsl:sort select="position()" data-type="number" order="descending"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
来源:https://stackoverflow.com/questions/25727860/xslt-how-to-reverse-the-tree