2010-09-08 171 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