Search code examples
xmlxsltprefix

NameSpace prefix for xsd:any elements and adding namespace prefix with XSLT


I am having trouble in working with the name space.

I get the input as below.

  <?xml version="1.0" encoding="UTF-8"?>

      <Org xmlns="http://mysample.org" >
        <Dept>
            <Person>
                <FirstName>Sample </FirstName>
                <LastName> Sampel L </LastName>
                <Address>
                    <Street>Sample Street</Street>
                    <House>45 Block C </House>
                    <State>Kentucky</State>
                    <AddExtension>
                        <ns3:LandMark xmlns:ns3="http://mysample.org" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                            <ns3:POI tag="temp">Sample POI </ns3:POI>
                        </ns3:LandMark>                         
                    </AddExtension>
            </Person>
        </Dept>
      </Org>

I need to add the namespace prefix to all the elements in this XML.

I tried the below XSL:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:ns3="http://mysample.org">

    <xsl:output omit-xml-declaration="no" indent="yes" />
    <xsl:strip-space elements="*" />

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

    <xsl:template match="*"> 
        <xsl:element name="ns3:{name()}" namespace="http://mysample.org">
            <xsl:copy-of select="@*"></xsl:copy-of>
            <xsl:copy-of select="namespace::*" />
            <xsl:apply-templates select="node()" />
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

But it is giving problem because of the AddExtension data in the input XML "

Note: the Data inside the "AddExtension" is coming based on the xsd:any tag as per the scema. So it will be different data for different input XMLs.

How can I overcome this?

Plese help.


Solution

  • Try this template instead:

    <xsl:template match="*"> 
        <xsl:element name="ns3:{local-name()}" namespace="{namespace-uri()}">
            <xsl:copy-of select="@*"/>
            <xsl:apply-templates select="node()" />
        </xsl:element>
    </xsl:template>