2012-02-16 13 views
1

我有一個多個實體(在我的例子中爲<data>)與鍵值對。每個實體都以相同的順序包含相同的密鑰,但我不知道是哪個和多少個。如何使用XSLT將其轉換爲HTML表格,在表頭中具有鍵和錶行中的實體的值?如何將XML與鍵值對的條目轉換爲HTML表格?

<data> 
    <entry> 
    <key>id</key><value>12345</value> 
    </entry> 
    <entry> 
    <key>price</key><value>12.45</value> 
    </entry> 
    <entry> 
     <key>country</key><value>UK</value> 
    </entry> 
<data> 
<data> 
    <entry> 
    <key>id</key><value>67890</value> 
    </entry> 
    <entry> 
    <key>price</key><value>67.89</value> 
    </entry> 
    <entry> 
     <key>country</key><value>DE</value> 
    </entry> 
<data> 

...應該成爲...

<tr><th>id</th><th>price</th><th>country</th></tr> 
<tr><td>12345</td><td>12.45</td><td>UK</td></tr> 
<tr><td>67890</td><td>67.89</td><td>DE</td></tr> 

回答

2

用途:

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

    <xsl:output method="xml" indent="yes"/> 

    <xsl:template match="/"> 
     <table> 
      <tr> 
       <xsl:for-each select="//data[1]/entry"> 
        <th> 
         <xsl:value-of select="key"/> 
        </th> 
       </xsl:for-each> 
      </tr> 

      <xsl:apply-templates select="//data"/> 
     </table> 
    </xsl:template> 

    <xsl:template match="data"> 
     <tr> 
      <xsl:apply-templates select="entry"/> 
     </tr> 
    </xsl:template> 

    <xsl:template match="entry"> 
     <td> 
      <xsl:value-of select="value"/> 
     </td> 
    </xsl:template> 
</xsl:stylesheet> 

輸出:

<table> 
    <tr> 
    <th>id</th> 
    <th>price</th> 
    <th>country</th> 
    </tr> 
    <tr> 
    <td>12345</td> 
    <td>12.45</td> 
    <td>UK</td> 
    </tr> 
    <tr> 
    <td>67890</td> 
    <td>67.89</td> 
    <td>DE</td> 
    </tr> 
</table> 
+0

你如何應用XSL的XML? – sinsedrix 2012-02-16 14:12:22

+0

@sinsedrix,你是什麼意思? – 2012-02-16 14:13:31

+0

我嘗試在XML頭中添加'<?xml-stylesheet href =「data.xsl」type =「text/xsl」?>',但它根本不會生成HTML :( – sinsedrix 2012-02-16 14:21:07