XSLT: Insert node in XML document


This is how you can insert a new node somewhere in an XML document using XSLT.

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

    <!-- Identity template, copies everything as is -->
    <xsl:template match="@*|node()">
            <xsl:apply-templates select="@*|node()"/>

    <!-- Override for target element -->
    <xsl:template match="targetNode">
        <!-- Copy the element -->
            <!-- And everything inside it -->
            <xsl:apply-templates select="@* | *"/>
            <!-- Add new node (or whatever else you wanna do) -->
            <xsl:element name="newNode"/>