Search code examples
xsltcopyinsertion

XSLT add node if node does not exist, append child if it does


I have the following XML:

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

I need to be able to copy everything but check if we are in /root/book/element2[@location='whateverfile'] . If we are here we need to check if the sibling element3 exists, if it does not we add a <element3>. If on the other hand it already exists we need to goto the child elements of it and find last() and append an element of our own say <element3child>.

So far i have come up with the following. But bear in mind i am new to XSLT and need some help with syntax etc.

<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>

Solution

  • <?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>