以表格格式将XML转换为HTML

时间:2011-01-18 13:37:44

标签: html xml xslt

我想将此xml内容更改为HTML表格

    <SSI>
        <data>
            <expanded>Chemical Research</expanded><abbre>Chem. Res.</abbre>
            <expanded>Materials Journal</expanded><abbre>Mater. J.</abbre>
            <expanded>Chemical Biology</expanded><abbre>Chem. Biol.</abbre>
            <expanded>Symposium Series</expanded><abbre>Symp. Ser.</abbre>
            <expanded>Biochimica Polonica</expanded><abbre>Biochim. Pol.</abbre>
            <expanded>Chemica Scandinavica</expanded><abbre>Chem. Scand.</abbre>
        <\data>
        <data>
            <expanded>Botany</expanded><abbre>Bot.</abbre>
            <expanded>Chemical Engineering</expanded><abbre>Chem. Eng.</abbre>
            <expanded>Chemistry</expanded><abbre>Chem.</abbre>
            <expanded>Earth Sciences</expanded><abbre>Earth Sci.</abbre>
            <expanded>Microbiology</expanded><abbre>Microbiol.</abbre>
        <\data>
    <\SSI>

尝试使用以下XSL

      <?xml version="1.0"?>
      <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
      <xsl:template match="/">
      <html>
      <head><title>Abbreviate</title></head>
      <body>
      <table border="1">
      <tr>
      <th>Expanded</th>
      <th>Abbre</th>
      </tr>
       <xsl:for-each select="SSI/data">
       <tr>
        <td><xsl:value-of select="expanded"/></td>
        <td><xsl:value-of select="abbre"/></td>
       </tr>
       </xsl:for-each>
      </table>
      </body></html>
      </xsl:template>
      </xsl:stylesheet>

我只获得了HTML表格格式的第一个数据标签条目

    Expanded               Abbre  
    -----------           --------------------  
    Chemical Research     Chem. Res  
    Botany                Bot.

如何获取HTMl中的所有值???

1 个答案:

答案 0 :(得分:2)

如果您清理XSLT并使用xsl:apply-templates而不是xsl:for-each,生活将变得更加简单。几乎没有理由使用xsl:for-each。试试这个:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:template match="/">
        <html>
            <head><title>Abbreviate</title></head>
            <body>
                <table border="1">
                    <tr>
                        <th>Expanded</th>
                        <th>Abbre</th>
                    </tr>
                    <xsl:apply-templates select='SSI/data/expanded'/>
                </table>
            </body></html>
    </xsl:template>

    <xsl:template match="expanded">
        <tr>
            <td><xsl:apply-templates/></td>
            <xsl:apply-templates select='following-sibling::abbre[1]'/>
        </tr>
    </xsl:template>

    <xsl:template match="abbre">
        <td><xsl:apply-templates/></td>
    </xsl:template>

</xsl:stylesheet>

通过使用应用的小模板,您可以简化样式表。此外,没有真正的理由在这里使用xsl:value-of - 内置模板将做正确的事情。您最终会得到更易于理解的更简单的模板。