2016-07-22 121 views
0

我想在這裏完成的是移動一個元素(包括它的子節點),然後在該元素內添加一個子節點,反之亦然。看來,我一次只能做一件事。是否有可能同時做到這一點?如何移動XML元素並使用XSLT同時添加子元素?

這裏是我的XML輸入

<?xml version="1.0" encoding="UTF-8"?> 
<catalog> 
    <box1> 
     <cd1> 
      <title>Title 1</title> 
      <artist>Bob Dylan</artist> 
      <year>1985</year> 
     </cd1> 
     <cd2> 
      <title>Title 2</title> 
      <artist>Bonnie Tyler</artist> 
      <year>1988</year> 
     </cd2> 
    </box1> 
    <box2> 
     <cd3> 
      <title>Title 3</title> 
      <artist>Metallica</artist> 
     </cd3> 
    </box2> 
</catalog> 

想有輸出這樣

<catalog> 
<box1> 
    <cd1> 
     <title>Title 1</title> 
     <artist>Bob Dylan</artist> 
     <year>1985</year> 
    </cd1> 
    <cd2> 
     <title>Title 2</title> 
     <artist>Bonnie Tyler</artist> 
     <year>1988</year> 
    </cd2> 
    <cd3> 
     <title>Title 3</title> 
     <artist>Metallica</artist> 
     <year>1990</year> 
    </cd3> 
</box1> 

正如你所看到的元素CD3移動和添加,以及子節點。

下面是我所做的,它只是移動元素,無論我放置代碼的順序如何。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="3.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 

    <xsl:strip-space elements="*"/> 

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

    <!-- add a child element --> 
    <xsl:template match="cd3"> 
     <xsl:copy> 
      <xsl:apply-templates/> 
      <year>1990</year> 
     </xsl:copy> 
    </xsl:template> 

    <!-- move node --> 
    <xsl:template match="/catalog"> 
     <xsl:copy> 
       <xsl:apply-templates /> 
       <xsl:copy-of select="box2/cd3"/> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="box2"/> 

</xsl:stylesheet> 

回答

0

變化<xsl:copy-of select="box2/cd3"/><xsl:apply-templates select="box2/cd3"/>和更改<xsl:template match="/catalog"><xsl:template match="/catalog/box1">

+0

Martin,我照你的建議做了,並且元素沒有顯示。 – user1998820

+0

@ user1998820,是的,它似乎與您的原始樣式表,它只是建議一些編輯有點困難,建議使用'apply-templates'是正確的,此外改變''xsl:template match =「/ catalog/box1「>'也簡化了方法,但我忽略了,那麼您還需要將apply-templates的路徑修改爲''。 –

0

我解決了下面的代碼。感謝您的幫助讓我開始進一步調查。

​​