Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to XML gets no data with schema set

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">
  <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

like image 795
SteveCl Avatar asked Dec 31 '22 09:12

SteveCl


1 Answers

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;
like image 70
Mark Cidade Avatar answered Jan 08 '23 16:01

Mark Cidade