用于对具有相同值的节点进行分组的XSLT表达式(当值未知时)?

时间:2012-03-12 18:54:49

标签: xml xslt xpath

XML文件:

<books>
    <scifi key=...>
       <author>Don Larson</author>
       <title>The Edge</title>
       <year>...</year>
    </scifi>
    <scifi key=...>
       <author>Don Larson</author>
       <author>James Kiddleton</author>
       <author>Danny Wobers</author>
       <title>Incognitum</title>
       <year>1987</year>
    </scifi>
    <scifi key=...>
       <author>....</author>
       <author>....</author>
       <title>...</title>
       <year>...</year>
    </scifi>
    etc......................
</books>

XSL文件:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <html>
  <body>
    <center><h3>Results :</h3>
    <table border="1">
    <tr>
      <th>Title</th>
      <th>Authors</th>
      <th>Pages</th>
      <th>Year</th>
    </tr>
      <xsl:for-each select=..............
      ...............
      ........ 

如何通过作者在我的XML文件中显示信息? Don Larson出现在两个头衔中,所以我想得到一张桌子,其中一个单元格的名字是Dan Larson,旁边的单元格有两个与Dan Larson相关的标题......等等。(顺便说一下:一个作者可能只有一个一个标题)

1 个答案:

答案 0 :(得分:1)

使用:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="author" match="scifi" use="author"/>

  <xsl:template match="/*">
    <table>
      <xsl:apply-templates select="scifi[generate-id() = generate-id(key('author', author))]"/>
    </table>
  </xsl:template>

  <xsl:template match="scifi">
    <tr>
      <td>
        <xsl:value-of select="author"/>
      </td>

      <td>
        <xsl:for-each select="key('author', author)">
          <xsl:value-of select="title"/>
          <xsl:if test="position() != last()">
            <br/>
          </xsl:if>
        </xsl:for-each>
      </td>
    </tr>
  </xsl:template>

</xsl:stylesheet>

输出:

<table>
  <tr>
    <td>Don Larson</td>
    <td>The Edge<br />Incognitum</td>
  </tr>
  <tr>
    <td>X</td>
    <td>...</td>
  </tr>
</table>