Tuesday, August 12, 2003 - Posts

Namespace Madness

Lately there has been a lot of talk about XML namespace.  Let’s boil it down to a very simplified example.  Namespaces can be distilled down to grouping or categorization.  We do this everyday.  We add namespaces to everything.  It helps us prevent “namespace collisions“.

My house = my:house

My car = my:car

My kid = my:kid

Neighborhood dog = neighborhood:dog

My yard = my:yard

And so on…

 

And context has everything to do with it.  As Tim Bray points out.  How the XML is consumed or transformed is up the application. Your parsing application has context.  A RSS reader will handle a RSS XML file differently than a SVG rendering engine would handle it.  The SVG rendering engine has no context of the RSS XML namespace.  The context it is defined by a set of people or entity (think W3) or the application.

 

This may be an over simplification and if it is, just call me simple!

 

Below is a very simple XSL that will give you a list of namespaces within your XML document along with an example.

 

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

<location xmlns:me="http://dotnetjunkies.com/webLog/metablog/"  xmlns:bug="http://www.ralphtheroach.com">

   <me:house>

      <me:me me:action="squash bug">Sean Gerety

         <bug:roach bug:action="looking for dinner">Ralph</bug:roach>

      </me:me>

   </me:house>

</location>

 

If you transform the above xml using the following xsl.

 

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

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="*">

      <xsl:element name="namespaceList">

      <xsl:element name="namespace">default or empty</xsl:element>

         <xsl:for-each select="namespace::*">

           <xsl:element name="namespace">

              <xsl:value-of select="."/>

           </xsl:element>

         </xsl:for-each>

      </xsl:element>

   </xsl:template>

</xsl:stylesheet>

You get.

 

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

<namespaceList>

   <namespace>default or empty</namespace>

   <namespace>http://www.w3.org/XML/1998/namespace</namespace>

   <namespace>http://dotnetjunkies.com/webLog/metablog/</namespace>

   <namespace>http://www.ralphtheroach.com</namespace>

</namespaceList>