2011-12-14 41 views
4

我想用xslt和一組行節點和列節點將XML文檔轉換爲xhtml表。xslt用可定製的標題創建動態表

列節點定義關於相關行屬性的數據。例如,第一個列節點指定Row節點的ID屬性應該隱藏(即不在表中顯示)。 Column節點的Caption元素定義了列標題文本應該是什麼。

我見過的解決方案,你知道你想要變成的提前列的屬性,但我不知道如何使用相關的列數據格式化頭

輸入:

<TableData> 
    <Columns> 
     <Column Name="ID" Hidden="true" /> 
     <Column Name="Name" Caption="Item Name" /> 
     <Column Name="Desc" Caption="Item Description" /> 
    </Columns> 
    <Rows> 
     <Row ID="0" Name="A" /> 
     <Row ID="1" Name="B" Desc="Some description"/> 
     <Row ID="3" Name="C" /> 
    </Rows> 
</TableData> 

所需的輸出將是(X)HTML這樣的一個表:

Item Name  | Item Description 
-------------------------------------- 
A    |  
B    | Some Description 
C    | 

回答

3

這種轉變

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 

<xsl:key name="RowAttribsByName" match="Row/@*" 
     use="concat(generate-id(..), '|', name())"/> 

<xsl:variable name="vColNames" select= 
    "/*/Columns/*[not(@Hidden = 'true')]/@Name"/> 

<xsl:template match="/*"> 
    <table border="1"> 
    <tr> 
    <xsl:apply-templates select="Columns/*"/> 
    </tr> 
    <xsl:apply-templates select="Rows/Row"/> 
    </table> 
</xsl:template> 

<xsl:template match="Column[not(@Hidden = 'true')]"> 
    <td><xsl:value-of select="@Caption"/></td> 
</xsl:template> 

<xsl:template match="Row"> 
    <tr> 
    <xsl:apply-templates select="$vColNames"> 
    <xsl:with-param name="pRowId" 
      select="generate-id()"/> 
    </xsl:apply-templates> 
    </tr> 
</xsl:template> 

<xsl:template match="Column/@*"> 
    <xsl:param name="pRowId"/> 

    <td width="50%"> 
    <xsl:value-of select= 
     "key('RowAttribsByName', 
      concat($pRowId, '|', .) 
      ) 
    "/> 
    </td> 
</xsl:template> 
</xsl:stylesheet> 

時所提供的XML文檔應用:

<TableData> 
    <Columns> 
     <Column Name="ID" Hidden="true" /> 
     <Column Name="Name" Caption="Item Name" /> 
     <Column Name="Desc" Caption="Item Description" /> 
    </Columns> 
    <Rows> 
     <Row ID="0" Name="A" /> 
     <Row ID="1" Name="B" Desc="Some description"/> 
     <Row ID="3" Name="C" /> 
    </Rows> 
</TableData> 

產生想要的,正確的結果

<table border="1"> 
    <tr> 
     <td>Item Name</td> 
     <td>Item Description</td> 
    </tr> 
    <tr> 
     <td width="50%">A</td> 
     <td width="50%"/> 
    </tr> 
    <tr> 
     <td width="50%">B</td> 
     <td width="50%">Some description</td> 
    </tr> 
    <tr> 
     <td width="50%">C</td> 
     <td width="50%"/> 
    </tr> 
</table> 
+0

很不錯!很好的工作 – cordialgerm 2011-12-14 05:09:53