如果节点不存在,则XSLT添加节点;如果节点存在,则追加子节点

如果节点不存在,则XSLT添加节点;如果节点存在,则追加子节点,xslt,copy,insertion,Xslt,Copy,Insertion,我有以下XML: <root> <book> <element2 location="file.txt"/> <element3> <element3child/> </element3> </book> <book> <element2 location="difffile.txt"

我有以下XML:

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



谢谢您的帮助。很好用。谢谢你的帮助。工作完美。
<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>
<?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>