2010-06-04 107 views
1

我有以下格式的xml文檔,並希望使用xsl模板進行轉換。遞歸xsl轉換

我是xsl轉換的初學者,我只需要知道如何緩衝槽樹,但整個問題的解決方案會很好。

這是XML文檔:

<?xml version="1.0" encoding="UTF-8" ?> 
<nodes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <node> 
     <type>Parent</type> 
     <name>.test</name> 
     <node> 
      <type>parent</type> 
      <name>.test.root</name> 
      <node> 
       <type>Parent</type> 
       <name>.test.root.group</name> 
       <node> 
        <type>int</type> 
        <name>.test.root.group.a</name> 
        <value>0</value> 
       </node> 
       <node> 
        <type>char</type> 
        <name>.test.root.group.b</name> 
        <value>-</value> 
       </node> 
      </node> 
     </node> 
     <node> 
      <type>parent</type> 
      <name>.test.versions</name> 
      <node> 
       <type>utf-8</type> 
       <name>.test.versions.version</name> 
       <value>alpha</value> 
      </node> 
      <node> 
       <type>utf-8</type> 
       <name>.test.version.extra</name> 
       <value>16.5</value> 
      </node> 
     </node> 
    </node> 
</nodes> 

這是我想怎麼產生的HTML看起來像:

 
    .---------------------------------------------. 
    | tree     | value  | type | 
    |------------------------+-----------+--------| 
    | '- test    |   | parent | 
    | |- root    |   | parent | 
    | | '- group   |   | parent | 
    | |  |- a   | 0   | int | 
    | |  '- b   | -   | char | 
    | '- versions   |   | parent | 
    |  |- version  | "alpha" | utf-8 | 
    |  '- extra   | 16.5  | utf-8 | 
    '---------------------------------------------' 
+0

如果你不想要XML輸出,你爲什麼要使用XSL? – Oded 2010-06-04 08:14:54

+0

請參閱更新(我希望輸出的格式與div/html相同) – dacwe 2010-06-04 08:42:57

+0

@Oded:XSL除了輸出XML外還有其他用途。僅舉幾例,它可以像dacwe想要的那樣輸出到html,如果使用XSL-FO它可以生成PDF文件,甚至可以生成另一個XSL文檔!如此多的選項和功能..它不僅限於生成xml :) – developer 2010-06-10 21:25:51

回答

3

這個XSLT會像你想生成的樹:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="text" indent="yes"/> 

    <xsl:template match="/"> 
    <xsl:apply-templates select="nodes/node"> 
     <xsl:with-param name="indent" select="''" /> 
     <xsl:with-param name="parent" select="''" /> 
    </xsl:apply-templates> 
    </xsl:template> 

    <xsl:template match="node"> 
    <xsl:param name="indent"/> 
    <xsl:param name="parent"/> 

    <xsl:value-of select="$indent" /> 
    <xsl:value-of select="substring-after(name/text(), $parent)" /> 
    <xsl:text>&#xa;</xsl:text> 

    <xsl:apply-templates select="./node"> 
     <xsl:with-param name="indent" select="concat($indent, ' |')" /> 
     <xsl:with-param name="parent" select="name/text()" /> 
    </xsl:apply-templates> 

    </xsl:template> 

</xsl:stylesheet> 

將數據添加到下兩欄非常簡單,請嘗試自行完成。