2010-10-01 70 views
0

節點的平面列表我如何轉換此XML轉換XML樹成使用XSL

<albums> 
    <album title="New Zealand"> 
     <album title="Auckland"> 
      <image title="Mt Eden railroad station"/> 
      <image title="Morgan St"/> 
     </album> 
    </album> 
    <album title="Russia"> 
     <image title="Capital of Siberia"/> 
    </album> 
</albums> 

<div class="level-0"> 
    New Zealand 
    Russia 
</div> 

<div class="level-1"> 
    Auckland 
</div> 

<div class="level-1"> 
    <img alt="Capital of Siberia"/> 
</div> 

<div class="level-2"> 
    <img alt="Mt Eden railroad station"/> 
    <img alt="Morgan St"/> 
</div> 

回答

1
<xsl:template match="/"> 
    <xsl:apply-templates select="/albums | //album"/> 
</xsl:template> 

<xsl:template match="albums | album"> 
    <div class="level-{count(ancestor-or-self::album)}"> 
    <xsl:apply-templates select="album/@title | image"/> 
    </div> 
</xsl:template> 

<xsl:template match="album/@title"> 
    <xsl:value-of select="concat(.,'&#xA;')"/> 
</xsl:template> 

<xsl:template match="image"> 
    <img alt="{@title}"/> 
</xsl:template> 
+1

尼克,這不行; 'xsl:value-of'不能是'xsl:apply-templates'元素的子元素。 – Flynn1179 2010-10-01 10:45:34

+0

@ Flynn1179:對不起現在應該修復。 – 2010-10-01 10:47:20

+2

如果訂單相關,您可以在第一個模板的'xsl:apply-templates'調用中添加''。 – Flynn1179 2010-10-01 10:52:16

3

這很難告訴你想從這個樣品到底該怎麼做,但通常,你可以用輕微修改的身份模板扁平化的XML樹:

<xsl:template match="@* | node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*"/> 
    </xsl:copy> 
    <xsl:apply-templates select="node()" /> 
</xsl:template> 

你可以可能會適應您的具體需求。

+0

+1爲一個很好的答案。 – 2010-10-01 12:42:46

+0

+1因爲如果訂單不相關,這是一個更好的答案。 – 2010-10-01 15:31:56