将多个节点中的数据提取到表中

时间:2016-08-19 07:49:07

标签: xml xslt xpath

到目前为止,我一直在使用forloops来构建包含记录的表格,但是我无法完成表格,因为我无法找到将剩余数据插入第三列的方法在另一个节点内。

我得到了什么

enter image description here

我想要什么

enter image description here

以下代码

XML

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="grades.xsl"?>
<school>
 <subject Id="3311">
 <className>English</className>
 <studentList>
 <student id="1001">Lisa Simpson</student>
 <student id="1002">Barney Rubble</student>
 <student id="1003">Donald Duck</student>
 </studentList>
 <classwork>
 <assignment name="Final Exam">
 <mark studId="1001">38</mark>
 <mark studId="1002">21</mark>
 <mark studId="1003">20.5</mark>
 </assignment>
 </classwork>
 </subject>
</school>

XSL(迄今为止)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <html>
  <body>
  <h2>My CD Collection</h2>
    <table border="1">
      <tr bgcolor="#9acd32">
        <th style="text-align:left">Student</th>
        <th style="text-align:left">ID</th>
        <th style="text-align:left">Mark</th>
      </tr>

      <xsl:for-each select="//student">
      <tr>
        <td><xsl:value-of select="."/></td>
        <td><xsl:value-of select="./@id"/></td>
      </tr>
      </xsl:for-each>

    </table>
  </body>
  </html>
</xsl:template>
</xsl:stylesheet>

1 个答案:

答案 0 :(得分:0)

您可以尝试以下样式表:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:strip-space elements="*"/>
    <xsl:output indent="yes"/>

    <!-- key for the target node for the mark column  -->        
    <xsl:key name="kID" match="mark" use="@studId"/>

    <xsl:template match="/">
        <table>
           <!-- set table headers -->
            <tr>
                <th>Student</th>
                <th>ID</th>
                <th>Mark</th>
            </tr>
        <!-- Loop through each target node -->
        <xsl:for-each select="school/subject/studentList/student">
            <tr>
                <td><xsl:value-of select="."/></td>
                <td><xsl:value-of select="@id"/></td>
                <!-- get the value using keys -->
                <td><xsl:value-of select="key('kID', @id)"/></td>
            </tr>
        </xsl:for-each>
        </table>
    </xsl:template>

</xsl:stylesheet>