2017-08-16 108 views
0
<?xml version="1.0"?> 
<?xml-stylesheet type="text/xsl" href="books.xsl"?> 
<bookList> 
    <Book BookId="3311"> 
     <BookName>Flying</BookName> 
     <readerList> 
      <readers sid="1001">Ashley</readers> 
      <readers sid="1002">Mark</readers> 
      <readers sid="1003">Donar</readers> 
     </readerList> 
     <readingItems> 
      <readings name="Assign 4" weight="20"> 
       <mark studId="1001">15</mark> 
       <mark studId="1002">18</mark> 
       <mark studId="1003">9</mark> 
      </readings> 
      <readings name="Assign 5" weight="25"> 
       <mark studId="1001">23</mark> 
       <mark studId="1002">14</mark> 
       <mark studId="1003">23</mark> 
      </readings> 
      <readings name="Essay" weight="15"> 
       <mark studId="1001">13</mark> 
       <mark studId="1002">12</mark> 
       <mark studId="1003">6</mark> 
      </readings> 
      <readings name="Exam" weight="40"> 
       <mark studId="1001">38</mark> 
       <mark studId="1002">25</mark> 
       <mark studId="1003">20.5</mark> 
      </readings> 
     </readingItems> 
    </Book> 
</bookList> 

这是书籍的数据。我无法更改格式。我不知道如何将readerList与读者合作。无论我做什么,它都不起作用。如何从书籍列表中获取数据XML表格

这是我的XSL片

​​

我想它显然在我指定的格式,但无论我做什么,我不能让它开始工作。

回答

1

您遇到的一个问题是您的XML有readerList,但您的XSLT有readersList。另外,您只有一个readerList,但您希望模板中的代码与每个reader输出一次,因此您可能需要选择reader元素。

试试这个XSLT

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="/"> 
    <html> 
     <body> 
     <table border="1"> 
      <tr> 
      <th>ID</th> 
      <th>Name</th> 
      <th>Total Mark</th> 
      <th>Grade</th> 
      </tr> 
      <xsl:apply-templates select="bookList/Book/readerList/readers"/> 
     </table> 
     </body> 
    </html> 
    </xsl:template> 
    <xsl:template match="readers"> 
    <tr> 
    <td><xsl:value-of select="@sid"/></td> 
    <td><xsl:value-of select="."/></td> 
    <td><xsl:value-of select="sum(../../readingItems/readings/mark[@studId = current()/@sid])"/></td> 
    </tr> 
    </xsl:template> 
</xsl:stylesheet> 

注意我还展示了如何获得积分,虽然这可能与使用xsl:key的改善。

这假设有在你的XML多本图书,并希望通过本书分离结果:

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

    <xsl:key name="marksByBook" match="mark" use="concat(../../../@BookId, '|', @studId)" /> 

    <xsl:template match="/"> 
    <html> 
     <body> 
     <table border="1"> 
      <tr> 
      <th>ID</th> 
      <th>Name</th> 
      <th>Total Mark</th> 
      <th>Grade</th> 
      </tr> 
      <xsl:apply-templates select="bookList/Book/readerList/readers"/> 
     </table> 
     </body> 
    </html> 
    </xsl:template> 
    <xsl:template match="readers"> 
    <tr> 
    <td><xsl:value-of select="@sid"/></td> 
    <td><xsl:value-of select="."/></td> 
     <td><xsl:value-of select="sum(key('marksByBook', concat(../../@BookId, '|', @sid)))"/></td> 
     <td>?</td> 
    </tr> 
    </xsl:template> 
</xsl:stylesheet> 

考虑到weight可能会更麻烦,并有可能保证一个新的问题...