How to fix problems with Linq to Xml Namespaces How to fix problems with Linq to Xml Namespaces

How to fix problems with Linq to Xml Namespaces

The Problem

You are trying to read data out of a standard xml file.  I found a great Linq to Xml tutorial here.  You get code that looks something like this

XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath("~/Invoices.xml"));
List<Invoice> lst = new List<Invoice>();
lst= (from c in data.Descendants("invoice")
select new Invoice
{
ClientName = c.Element("client").Value,
InvoiceDate = Convert.ToDateTime(c.Element("date").Value),
}).ToList();

and you get nothing but object type no found errors.  Why?  You have problems with linq to xml namespaces.

The Cause:

The xml file you are trying to read is using a NameSpace!

The Solution:

Add in the namespace declaration and append it to the file in the right places, your code should look something like the below.

XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath(“~/Invoices.xml”));
XNamespace ns = XNamespace.Get(“http://www.SomeProvider.com/api”);
List lst = new List();
lst= (from c in data.Descendants(ns + “invoice”)
select new Invoice
{
ClientName = c.Element(ns + “client”).Value,
InvoiceDate = Convert.ToDateTime(c.Element(ns + “date”).Value),
}).ToList();

Do you see the “ns + ” part?  That tells C# to keep your data and the xml data apart.  And please note, you have to use it everywhere you reference a part of the xml document (I spent an hour finding that out).

That’s it!  Happy Coding.

Tags:

 

Written By Steve French

 

One response to “How to fix problems with Linq to Xml Namespaces”

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.