开发者

printing a count with XSLT

I have an XML file which I'm trying to transform into XHTML using a XSLT file. I was wondering if it's possible to get a count of the number of times a template has been invoked. This is my XML:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" encoding="UTF-8" href="car.xslt" version="1.0"?>
<vehicle>
  <car>
    <make>Honda</make>
    <color>blue</color>
  </car>
  <car>
    <make>Saab</make>
    <color>red</color>
  &l开发者_如何学JAVAt;/car>
</vehicle>

And this is my XSLT:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml" version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
  <table cellpadding="5" border="1">
    <tr><td>number</td><td>make</td><td>color</td></tr>
        <xsl:apply-templates/>
  </table>
</body>
</html>
</xsl:template>

<xsl:template match="car">
    <tr>
      <td>#</td><td><xsl:value-of select="make"/></td><td><xsl:value-of select="color"/></td>
    </tr>
</xsl:template>

</xsl:stylesheet>

I want to print the number of times a car has been printed in the place of #, so it would look like this:

number make color 1 Honda blue 2 Saab red

instead of:

number make color # Honda blue # Saab red

Anybody have any ideas? I was hoping this could be done with just xsl:value-of and XPath


Replace

#

With

<xsl:value-of select="position()"/>


You can rearrange this a bit so that instead of using <xsl:apply-templates/>, do something like this:

<tr><td>number</td><td>make</td><td>color</td></tr>
<xsl:for-each select="/vehicle/car">
  <tr>
    <td><xsl:value-of select="position()" /></td><td>...</td>
  </tr>
</xsl:for-each>

In this case, the position() function will refer to the iteration number of the associated for-each loop. This may give you what you're looking for.


Minimal change:

<xsl:stylesheet 
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns="http://www.w3.org/1999/xhtml"
>
  <xsl:template match="/vehicle">
    <html>
      <body>
        <table cellpadding="5" border="1">
          <tr>
            <td>number</td>
            <td>make</td>
            <td>color</td>
          </tr>
          <xsl:apply-templates select="car" />
        </table>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="car">
    <tr>
      <td><xsl:value-of select="position()" /></td>
      <td><xsl:value-of select="make" /></td>
      <td><xsl:value-of select="color" /></td>
    </tr>
  </xsl:template>

</xsl:stylesheet>

Note the select="car" attribute on the <xsl:apply-templates>. It makes sure that only <car> nodes are counted, so your position() is not off.

Also note that the main template now matches the document element, not the root node.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜