XSLT against XML with a default namespace (xmlns=””)

I’ve been doing quite a bit with serialization and today with XSLT to make the .xml presentable. I ran across a scenario that took me some time to find the answer to. Suppose you have an .xml file that has a default namespace, something like:

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

<data xmlns="http://schemas.somecompany.com/2008/03/someApp">

  <customers>

    <customer firstName="John" lastName="Doe"/>

  </customers>

</data>

Now, when you go to create your XSLT, you will find it won’t find your xpath’s like you might expect – for example:

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

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

    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">

    <xsl:template match="/">

      Customers:

      <hr/>

      <ul>

      <xsl:for-each select="data/customers/customer">

        <li><xsl:value-of select="@firstName"/> <xsl:value-of select="@lastName"/></li>

      </xsl:for-each>

      </ul>

    </xsl:template>

</xsl:stylesheet>

this is because the XML file has a default namespace (the xmlns="") and your XSLT doesn’t reference it. So, to make it so your XSLT can find the xpath within your XML document, you just have to reference it, give it a namespace prefix – and use that prefix in your XSLT, for example (you can call the prefix whatever you want):

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

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

    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"

    xmlns:test="http://schemas.somecompany.com/2008/03/someApp">

    <xsl:template match="/">

      Customers:

      <hr/>

      <ul>

      <xsl:for-each select="test:data/test:customers/test:customer">

        <li><xsl:value-of select="@firstName"/> <xsl:value-of select="@lastName"/></li>

      </xsl:for-each>

      </ul>

    </xsl:template>

</xsl:stylesheet>

Note that you would need to include that prefix anywhere in your XSLT where you are referencing the elements from that namespace – but not the attributes.

Posted in Uncategorized, XML stuff
One comment on “XSLT against XML with a default namespace (xmlns=””)
  1. jflo says:

    Thank you!!!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives
Categories

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

Join 2 other followers

%d bloggers like this: