2010-09-08 265 views
0

林與PHP5的工作,我需要在下面的表格來轉換XML:複製節點屬性父節點

<section> 
     <heading> 
      <line absolutePage="4" page="2" num="35">A Heading</line> 
     </heading> 
     <subsection type="type1"> 
      <heading label="3"> 
        <line absolutePage="4" page="2" num="36">A Subheading</line> 
      </heading> 
      <content/> 
     </subsection> 
</section> 

弄成這個樣子:

<section name="A Heading"> 
     <heading> 
      <line absolutePage="4" page="2" num="35">A Heading</line> 
     </heading> 
     <subsection type="type1" label="3" name="A Subheading"> 
      <heading label="3"> 
        <line absolutePage="4" page="2" num="36">A Subheading</line> 
      </heading> 
      <content/> 
     </subsection> 
</section> 

注意,label屬性有已從標題屬性複製到父元素。

此外,heading/line元素的文本已添加爲heading父節點的屬性。

回答

3

這個樣式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="subsection"> 
     <subsection label="{heading/@label}" name="{heading/line}"> 
      <xsl:apply-templates select="@*|node()"/> 
     </subsection> 
    </xsl:template> 
    <xsl:template match="section"> 
     <section name="{heading/line}"> 
      <xsl:apply-templates select="@*|node()"/> 
     </section> 
    </xsl:template> 
</xsl:stylesheet> 

輸出:

<section name="A Heading"> 
    <heading> 
     <line absolutePage="4" page="2" num="35">A Heading</line> 
    </heading> 
    <subsection label="3" name="A Subheading" type="type1"> 
     <heading label="3"> 
      <line absolutePage="4" page="2" num="36">A Subheading</line> 
     </heading> 
     <content></content> 
    </subsection> 
</section> 

注意:只要是更多鈔票用文字結果元素和屬性值模板,使用它。這使得代碼緊湊和快速。如果你想更普遍的答案,請澄清。

編輯:錯過section/@name。當然,如果空字符串section/@label不打擾你,你可以使用section|subsection模式匹配。

+0

@Alejandro,謝謝偉大的工作,只是添加'匹配'的OR匹配,這是缺少。 :) – 2010-09-08 15:36:34

+0

@Benjamin Ortuzar:你很好。我也更新了答案。 – 2010-09-08 15:53:56

+0

+1用於使用和覆蓋Identity變換以及使用AVT – 2010-09-08 17:45:05