Mark's Blog

.Net, C#, VB.Net, SQL, WPF, Silverlight, WCF, ASP.Net, EF

Wednesday, April 8, 2009

LINQ to XML and Namespaces

Today I was using a LINQ query to extract some data from an XML document but was not getting the expected results. I had used the same query pattern in the past and was puzzled to why it was not working.

I had the following XML.

   1: <SomeResults xmlns="http://www.someplace.com/api">
   2:   <Status>GOOD</Status>
   3: </SomeResults>

This was my original query.

   1: var courseStatusReqestResult = XDocument.Parse(@"<SomeResults xmlns=""http://www.someplace.com/api"">
   2:                                                     <Status>GOOD</Status>
   3:                                                  </SomeResults>");
   4:                                                  
   5: var response = from c in courseStatusReqestResult.Elements("SomeResults")
   6:                                              select c.Element("Status");
   7: response.Dump();
 
I was expecting the Status element to be returned, however response was null. After running some tests in LINQPad it turns out that the XML namespace attribute was throwing it off.
 
To fix this I had to add the namespace to the elements in the LINQ query.
 
   1: var courseStatusReqestResult = XDocument.Parse(@"<SomeResults xmlns=""http://www.someplace.com/api"">
   2:                                                     <Status>GOOD</Status>
   3:                                                  </SomeResults>");
   4:                                                  
   5: XNamespace ns = "http://www.someplace.com/api";
   6:  
   7: var response = from c in courseStatusReqestResult.Elements(ns + "SomeResults")
   8:                                              select c.Element(ns + "Status");
   9: response.Dump();
 
The results
 
image
 
 

No comments:

Post a Comment