1

There's a lot of references in the internet that has the same problem with me. It is the adding of namespace, I have the same as this one that I saw: Adding namespace in inner parent group in xslt v2.0. But in my case, I don't have a namespace in the parent tag and insert the namespace in the inner level group. I tried to copied the solutions but I can't get the expected output. For example, I have this sample file,

INPUT:

<Record>
 <Data>
   <Section>
     <ID>111222</ID>
   </Section>
 </Data>
</Record>

EXPECTED:

<Record>
 <Data>
   <Section xmlns="www.hdgd.co">
     <ID>111222</ID>
   </Section>
 </Data>
</Record>

XSLT:

<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="*"/>
<xsl:template match="*">
    <xsl:element name="{local-name()}">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>
<xsl:template match="Section">
    <Section xmlns="www.hdgd.co">
        <xsl:copy-of select="*"/>
    </Section>
</xsl:template>

The generated output populated an empty namespace in the ID element. And, I need to remove that empty xmlns. Look like this:

    <Record>
 <Data>
   <Section xmlns="www.hdgd.co">
     <ID xmlns="">111222</ID>
   </Section>
 </Data>
</Record>
1
  • Don't think of it as "adding a namespace". Think of it as changing the name of the element. If you get the names of the elements right, the namespace declarations will look after themselves. The name of an element is a (namespace URI, local-name) pair. Commented May 31, 2017 at 10:10

1 Answer 1

1

You cannot use:

<xsl:copy-of select="*"/>

because that copies the child nodes in their original namespace - which is no-namespace. To get the result you want, you must move not only Section to the new namespace, but also all its descendants (and leave all other nodes as they are) - for example:

XSLT 1.0

<xsl:stylesheet version="1.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-or-self::Section]">
    <xsl:element name="{name()}" namespace="www.hdgd.co">
        <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @michael.hor257k for the feedback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.