2011-10-14 37 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

相关问题