开发者

Segregate top element out of a list using XSL

开发者 https://www.devze.com 2022-12-28 23:18 出处:网络
I currently have a <xsl:foreach> statement in my XSL processing all elements in this XML file.What I want to do though is process the first one separately to the rest.How can I achieve this?

I currently have a <xsl:foreach> statement in my XSL processing all elements in this XML file. What I want to do though is process the first one separately to the rest. How can I achieve this?

Here is my current code:

<ul>
    <xsl:for-each select="UpgradeProgress/Info">
        <xsl:sort select="@Order" order="descending" data-type="number" lang="en"/>
        <li><xsl:value-of select开发者_C百科="." /></li>
    </xsl:for-each>
</ul>


Assuming that you want to handle the first sorted element, this tests for the position inside of a choose statement and handles them differently:

<ul>
    <xsl:for-each select="UpgradeProgress/Info">
        <xsl:sort select="@Order" order="descending" data-type="number" lang="en"/>
        <li>
            <xsl:choose>
                <xsl:when test="position()=1">
                    <!-- Do something different with the first(sorted) Info element -->

                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="." />
                </xsl:otherwise>
            </xsl:choose>
        </li>
    </xsl:for-each>
</ul>


XSLT templates are your friends!

This transformation:

<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="/*">
     <ul>
       <xsl:apply-templates/>
     </ul>
 </xsl:template>

 <xsl:template match="num">
   <li>
     <xsl:value-of select="."/>
   </li>
 </xsl:template>

 <xsl:template match="num[1]">
   <li>
     <b><xsl:value-of select="."/></b>
   </li>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

produces the wanted special processing of the first (top) of the <num> elements:

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10

Do note, that you even don't have to use an <xsl:if> or <xsl:choose> in your code.

Use the enormous power of templates as much as possible.


you can select your element with the position function in xpath

http://www.w3schools.com/xpath/xpath_functions.asp

0

精彩评论

暂无评论...
验证码 换一张
取 消