2013-02-22 62 views
1

我有郵元素的根元素內的層次結構,像如何移動xml元素並同時更改屬性值?

<gliederung> 
    <posten id=".." order="1"> 
     <posten id=".." order"1"> 
      <posten id=".." order"1"> 
       ... 
      </posten> 
      <posten id="AB" order"2"> 
       ... 
      </posten> 
      ... 
     </posten> 
     <posten id=".." order"2"> 
      ... 
     </posten> 
     <posten id="XY" order"3"> 
      ... 
     </posten> 
    .... 
</gliederung> 

每個郵報具有唯一的ID和順序屬性。 現在我需要在id爲「AB」的元素之前移動ID爲「XY」的元素,並將移動元素「XY」的順序屬性更改爲「1.5」。

我設法元素與下面的腳本移動:

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

<xsl:template match="posten[@id='AB']"> 
    <xsl:copy-of select="../posten[@id='XY']"/> 
    <xsl:call-template name="identity"/> 
</xsl:template> 

<xsl:template match="posten[@id='XY']"/> 

但如何移動與改變順序屬性值爲「1.5

我缺少明顯的東西我想結合...

回答

1

相反的copy-of,使用模板

<!-- almost-identity template, that does not apply templates to the 
     posten[@id='XY'] --> 
<xsl:template match="node()|@*" name="identity"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()[not(self::posten[@id='XY'])]|@*"/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="posten[@id='AB']"> 
    <!-- apply templates to the XY posten - this will copy it using the 
      "identity" template above but will allow the specific template 
      for its order attr to fire --> 
    <xsl:apply-templates select="../posten[@id='XY']"/> 
    <xsl:call-template name="identity"/> 
</xsl:template> 

<!-- fix up the order value for XY --> 
<xsl:template match="posten[@id='XY']/@order"> 
    <xsl:attribute name="order">1.5</xsl:attribute> 
</xsl:template> 

如果您不確定XY位置相對於AB位置的確切位置(即,將它永遠是../posten[@id='XY']或它有時可能../../),那麼你可以定義一個

<xsl:key name="postenById" match="posten" use="@id" /> 

然後更換<xsl:apply-templates select="../posten[@id='XY']"/>

<xsl:apply-templates select="key('postenById', 'XY')"/> 
+0

酷,完美的作品! – Holger 2013-02-22 12:55:16