LINQ to XML does not receive data with a set of schemas

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

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

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

There are many CarForSale elements.

When the circuit is installed, and I do it ...

 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 the results that get Enumeration, and give no results

Extract the xmlns from the XML file and the data will return as expected.

Any ideas?

thanks

+4
source share
2 answers

You need to add a 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; 
+7
source

To avoid hard coding the namespace, you can use this:

 XNamespace ns = doc.Root.Name.Namespace; 
+3
source

Source: https://habr.com/ru/post/1277521/


All Articles