views:

1157

answers:

3

Hi

I am trying to get some XML data with LINQ, but running into a problem.

I am using a schema, which is set in the attribute xmlns ...

<CarsForSale xmlns="http://schemas.sharplogic.net/CarSales.xsd"&gt;
  <CarForSale>

There are many CarForSale elements.

When the schema is set and I do this...

XElement doc = XElement.Load(HttpContext.Current.Server.MapPath("App_Data/XML/CarsForSale.xml"));

var cars2 = from d in doc.Descendants("CarForSale")
            select d;

Then I get in the results i get Enumeration yielded no results

Strip the xmlns out of the XML file and the data comes back as expected??

Any ideas?

Thx

+4  A: 

You need to prepend the namespace:

var ns    = "http://schemas.sharplogic.net/CarSales.xsd";
var cars2 = from d in doc.Descendants(ns + "CarForSale")            
            select d;

otherwise search by local name:

var cars2 = from d in doc.Descendants()
            where d.Name.LocalName == "CarForSale"            
            select d;
Mark Cidade
A: 

Ahhh....that makes sense!

Thx.

SteveCl
+2  A: 

to avoid hard coding the namespace you can use this

XNamespace ns = doc.Root.Name.Namespace;

Muhammad Sami Ahmed