Reputation: 125
I'm trying to change the namespace of an element attribute using the below xsl code:
<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:ns2="http://www.ean-ucc.org/schemas/1.3.1/eanucc">
<xsl:output encoding='UTF-8' indent='yes' method='xml'/>
<!-- copy everything into the output -->
<xsl:template match='@*|node()'>
<xsl:copy>
<xsl:apply-templates select='@*|node()'/>
</xsl:copy>
</xsl:template>
<xsl:template match="IRenvelope">
<IRL xmlns:xsd="http://www.xx.com">
<xsl:copy-of select="node()|@*"/>
</IRL>
</xsl:template>
</xsl:stylesheet>
The xml message i use for testing is:
<GMessage xmlns="http://www.giffgaff.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<body>
<IRenvelope xmlns="http://www.mnv.com/elc/sap">
<Keys>
<Key Type="TaxOfficeNumber">635</Key>
</Keys>
</IRenvelope>
</body>
</GMessage>
I couldnt make it work and the namespace is not changing but provinding the same result. any help please?
The output xml to be as follows:
<GMessage xmlns="http://www.giffgaff.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<body>
<IRenvelope xmlns="http://www.xx.com">
<Keys>
<Key Type="TaxOfficeNumber">635</Key>
</Keys>
</IRenvelope>
</body>
</GMessage>
Upvotes: 1
Views: 9858
Reputation: 5432
The below XSLT will help you to get the desired results:
<xsl:stylesheet
version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsd="http://www.xx.com"
xmlns:ns="http://www.mnv.com/elc/sap"
exclude-result-prefixes="ns">
<xsl:output encoding='UTF-8' indent='yes' method='xml'/>
<!-- copy everything into the output -->
<xsl:template match='@*|node()'>
<xsl:copy>
<xsl:apply-templates select='@*, node()'/>
</xsl:copy>
</xsl:template>
<!-- template to match ns:IRenvelope element and creating a new element -->
<xsl:template match="ns:IRenvelope">
<xsl:element name="IRL" namespace="http://www.xx.com">
<xsl:apply-templates select="@*, node()"/>
</xsl:element>
</xsl:template>
<!-- template to change the namespace
of the elements
from "http://www.mnv.com/elc/sap"
to "http://www.xx.com" -->
<xsl:template match="ns:*">
<xsl:element name="{local-name()}" namespace="http://www.xx.com">
<xsl:apply-templates select="@*, node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
Here, the last two templates match the ns:IRenvelope
and all the elements with namespace http://www.mnv.com/elc/sap
, respectively. Using the xsl:element
and its namespace attribute, we can create the new elements with desired namespace.
You can also declare the desired namespaces with prefixes and create elements as below:
<xsd:IRL xmlns:xsd="http://www.xx.com">
...
</xsd:IRL>
For XSLT-1.0:
Just replace the ,
(comma) to use a |
(pipe) in apply-templates as using comma to sequence the action is supported in 2.0:
<xsl:apply-templates select="@* | node()"/>
Upvotes: 4