XSLT:Sorting an XML based on multiple attributes
I have the following xml and I need to sort this xml using XSLT based on the value of
the "CONTENT_L开发者_JS百科ENGTH" KEY ie. based on the attributes in the element <DOC_DETAIL
KEY="CONTENT_LENGTH" VALUE="14"/>
<?xml version="1.0" encoding="UTF-8"?>
<DOC_LISTS>
<DOC_LIST>
<DOC_URL>testurl4</DOC_URL>
<DOC_DETAILS>
<DOC_DETAIL KEY="TITLE" VALUE="Red Dragon"/>
<DOC_DETAIL KEY="LANGUAGE" VALUE="english"/>
<DOC_DETAIL KEY="CONTENT_LENGTH" VALUE="14"/>
</DOC_DETAILS>
</DOC_LIST>
<DOC_LIST>
<DOC_URL>testurl2</DOC_URL>
<DOC_DETAILS>
<DOC_DETAIL KEY="TITLE" VALUE="Hannibal Rising"/>
<DOC_DETAIL KEY="LANGUAGE" VALUE="english"/>
<DOC_DETAIL KEY="CONTENT_LENGTH" VALUE="7"/>
</DOC_DETAILS>
</DOC_LIST>
</DOC_LISTS>
What will be the sort select statement in <xsl:sort select=""/>?
You will want DOC_DETAILS/DOC_DETAIL[@KEY='CONTENT_LENGTH']/@VALUE
Full simple example using Identity template
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="//DOC_LISTS">
<xsl:for-each select="DOC_LIST">
<xsl:sort select="DOC_DETAILS/DOC_DETAIL[@KEY='CONTENT_LENGTH']/@VALUE" data-type="number"/>
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:for-each>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
When using the Identity Transformation is really immediate sort the value just applying templates as follows:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="DOC_LISTS">
<xsl:copy>
<xsl:apply-templates select="DOC_LIST">
<xsl:sort select="
DOC_DETAILS
/DOC_DETAIL[@KEY='CONTENT_LENGTH']
/@VALUE" data-type="number"/>
</xsl:apply-templates>
</xsl:copy>
</xsl:template>
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
精彩评论