XSLT: how to reverse the tree?

家住魔仙堡 提交于 2019-12-25 02:34:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!