2011-10-14 38 views
1

我有下面的XML:XSLT添加節點,如果節點不存在,追加的孩子,如果它確實

<root> 
    <book> 
     <element2 location="file.txt"/> 
     <element3> 
      <element3child/> 
     </element3> 
    </book> 
    <book> 
     <element2 location="difffile.txt"/> 
    </book> 
</root> 

我需要能夠複製的一切,但是否我們在/根/電子書/ element2的[@ location ='whateverfile']。如果我們在這裏,我們需要檢查是否存在兄弟元素3,如果我們不添加<element3>。另一方面,如果它已經存在,我們需要轉到它的子元素,並找到last()並追加我們自己說的元素<element3child>

到目前爲止,我已經想出了以下內容。但要記住我是新來的XSLT和需要一些幫助,語法等

<xsl:template match="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 
<xsl:template match="/root/book/element2[@location='file.txt']/../*/last()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
    <element3child/> 
</xsl:template> 

回答

1
<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output indent="yes" /> 

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

    <!--If an <element2> has an <element3> sibling, 
      then add <element3child> as the last child of <element3> --> 
    <xsl:template match="/root/book[element2[@location='file.txt']] 
          /element3/*[position()=last()]"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
     <element3child/> 
    </xsl:template> 

    <!--If the particular <element2> does not have an <element3> sibling, 
      then create one --> 
    <xsl:template match="/root/book[not(element3)] 
          /element2[@location='file.txt']"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
     <element3/> 
    </xsl:template> 

</xsl:stylesheet> 
+0

感謝您的幫助。完美的作品。 – sledgehammer

相關問題