Alex Rivera | Logout

How to ignore namespaces during xsl translation time

Asked 2011-06-06T14:04:00.803
10

I have an xml as below.

<?xml version="1.0" encoding="UTF-8"?>
<books xmlns="http://www.books.com/SRK">
    <name>English</name>
</books

I required the following output after translation using xsl .

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <name>English</name>
</books>

I need an xsl to ignore the namespace.I have tried something but its not working with namespace.

I need your help.Your help would be appreciated.

Edit
Report

2 Answers

6

This transformation:

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

 <xsl:template match="@*|node()[not(self::*)]">
  <xsl:copy/>
 </xsl:template>

 <xsl:template match="*">
  <xsl:element name="{local-name()}">
   <xsl:apply-templates select="node()|@*"/>
  </xsl:element>
 </xsl:template>
</xsl:stylesheet>

when applied to the provided XML document:

<books xmlns="http://www.books.com/SRK">
    <name>English</name>
</books>

produces the wanted, correct result:

<books>
   <name>English</name>
</books>
answered 2011-06-06T14:37:00.130
3

Its working only if i include the above templates if i add some other templates other than the above one then the translation is not at all working .None of the template getting executed.

Probably you are missing the declaration of the namespace for the book element. Example:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:b="http://www.books.com/SRK"
    exclude-result-prefixes="b">

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

        <!-- @dimitre's answer templates -->

    <xsl:template match="b:name">
          <!-- your template for name -->
    </xsl:template>

</xsl:stylesheet>

Moreover, make sure to use local-name() function to get the name of an element without the related namespace.


Example

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:b="http://www.books.com/SRK"
    exclude-result-prefixes="b">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>


    <xsl:template match="b:input">
        <xsl:element name="{local-name(.)}">
                <xsl:apply-templates select="b:name"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="b:name">
        <xsl:element name="{local-name()}">
            <xsl:value-of select="."/>
        </xsl:element>
            <lhs>
                <xsl:apply-templates select="following-sibling::b:lhs/b:evaluate"/>
            </lhs>
    </xsl:template>

    <xsl:template match="b:evaluate">
        Something to evaluate...    
    </xsl:template>

</xsl:stylesheet>

gets:

<?xml version="1.0" encoding="UTF-8"?>
<input>
answered 2011-06-06T19:46:48.027

Your Answer