Namespaces and the XmlDataSource Server Control

Scott Hanselman discussed this earlier, but the XmlDataSource control has a bug in it. When working with the XPath capablities of the control (which you will do pretty much every time you use the control), the control will throw an exception when working with XML data that includes namespaces/prefixes. I recently encountered this problem when I was working with some of the XML data coming from the Amazon APIs.

One possible fix is to apply a XSLT stylesheet to strip the namespaces and prefixes from the XML. The XSL doc you would use would look as follows:

<?xml version="1.0" encoding="UTF-8"?>
<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:template match="*">
      <!-- Remove any prefixes -->
      <xsl:element name="{local-name()}">
          <!-- Work through attributes -->
          <xsl:for-each select="@*">
             <!-- Remove any attribute prefixes -->
             <xsl:attribute name="{local-name()}">
                <xsl:value-of select="."/>
             </xsl:attribute>
          </xsl:for-each>
      <xsl:apply-templates/>
      </xsl:element>
   </xsl:template>
</xsl:stylesheet>

Then with the XSL doc in place, you can then use the XmlDataSource control to make use of this document:

<asp:XmlDataSource ID="XmlDataSource1" runat="server"
 DataFile="NamespaceFilled.xml" TransformFile="~/RemoveNamespace.xsl"
 XPath="ItemLookupResponse/Items/Item"></asp:XmlDataSource>
posted @ Monday, October 10, 2005 4:55 AM
Print

Comments on this entry:

# re: Namespaces and the XmlDataSource Server Control

Left by Justin S at 1/25/2006 10:17 AM
Gravatar
Bill - this problem appears to not be fixed in the release version of ASP.NET 2.0. Can you confirm that, and are there any better work-arounds you've found? Thanks!

# re: Namespaces and the XmlDataSource Server Control

Left by Bill Evjen at 10/12/2006 10:27 PM
Gravatar
Yeah, it was something that was never addressed in the final release of .NET 2.0.

# re: Namespaces and the XmlDataSource Server Control

Left by Oussama Dinia at 6/28/2009 12:00 PM
Gravatar
Thank youuuu!

Years later, it's still a nice tip.

:)

Thanks to you and Scott Hanselman blogging on this, it took me 20 min to get around the problem.

thanks again!

Your comment:



(not displayed)

 
 
 
 
 

Live Comment Preview:

 
«July»
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789