Insert schemaLocation in the XML File using XSLT v2.0

You need to add a template matching Document only and add the attribute there (and only there). Then change your existing template so that it matches only descendants of Document:

<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

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

<xsl:template match="*[ancestor::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>

<xsl:template match="Document">
    <Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:apply-templates select="*"/>
    </Document>
</xsl:template>

</xsl:stylesheet>

Leave a Comment