If you are using ColdFusion XPath functions to search/parse XML strings, you will probably have come across this one at some point.  Not all, but most of the XML files have namespaces in them e.g. xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”. If you use Xpath on a string that contains namespaces, chances are that you will get back the namespaces as well and sometimes you dont want these at all. You just want to deal with the real data.

Now, if you use the local-name() function in Xpath, it gives you the attribute/element name without the namespace. So, you could do something like this to get all ‘a’ elements e.g.

 <cfset allLinks = XmlSearch(myXml, “//*[local-name()='a']“)>

<p>But , what if you want to get rid of the namespaces before you even start parsing, so you dont have to worry about it ?</p> <p>You can use the XmlTransform() available in ColdFusion to apply a XSL stylesheet to the XML document and the XSL template will make sure that you dont get any namespaces back. Here is a little code example.</p>

<cffunction name="removeNameSpaces" access="private" output="false">
<cfargument name="xmlNode" required="true" />

<cfsavecontent variable="myxsl">
<xsl:stylesheet xmlns:xsl ="http://www.w3.org/1999/XSL/Transform" version ="1.0" >
<xsl:template match ="@*" >
<xsl:attribute name ="{local-name()}" >
<xsl:value-of select ="." />
</xsl:attribute>
<xsl:apply-templates/>
</xsl:template>
<xsl:template match ="*" >
<xsl:element name ="{local-name()}" >
<xsl:apply-templates select ="@* | node()" />
</xsl:element>
</xsl:template>
</xsl:stylesheet>
</cfsavecontent>
<!--- apply the xsl--->
<cfreturn XmlTransform(arguments.xmlNode, myxsl) />
</cffunction>

I have not used much of XSLT in the past but I can tell that this XSLT only selects local-name() elements which means namespaces will be ignored completely.

Now, I am not sure if there any performance hits doing it this way but I thought it was cool to be able to do this.

Tagged with:  

4 Responses to Removing NameSpaces from XML using XSLT and ColdFusion

  1. Dave Kopecek says:

    Thank you ! Worked perfectly.

  2. julian897 says:

    can you give me a complete example of how to remove a xml namspaces?

  3. Aboo says:

    it worked…thanks

Leave a Reply

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 445 other subscribers

© 2011 Anuj Gakhar
%d bloggers like this: