How to parse xml data with dynamic linq

c# dynamic-linq linq xml


i am reading a xml file and querying by LINQ this below way

XDocument document = XDocument.Load(xmlFilePath);
var query = document.Descendants("orders").Select(c => c);
query = query.OrderBy(sortColumn + " " + OrderDirection);

query = query.Skip(lowerPageBoundary - 1 * rowsPerPage).Take(rowsPerPage);

DataTable table = query.ToList().ConvertToDataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
return table;

but getting error No property or field 'OrderID' exists in type 'XElement' (at index 0)

this is my sample xml which i am querying by LINQ

<?xml version="1.0" encoding="utf-8"?>
    <ShipName>Vins et alcools Chevalier</ShipName>
    <ShipAddress>59 rue de l'Abbaye</ShipAddress>

i used this below query but still no luck

var query = document.Descendants("orders")
                    .OrderBy(String.Format("Element(\"{0}\").Value {1}", sortColumn, OrderDirection))
                    .Skip(lowerPageBoundary - 1 * rowsPerPage)
7/22/2015 6:25:12 PM

Popular Answer

The reason you are getting the error is because XML tags are case sensitive.

An excerpt from the link (modified to match the example in your question):

XML tags are case sensitive. The tag <Orders> is different from the tag <orders>.

Your query is searching for the non-existing element "orders". Update your query:

XDocument document = XDocument.Load(xmlFilePath);
var query = document.Descendants("Orders").Select(c => c);


Based on your comments, the error is actually rooted in attempting to order by "OrderID" within the IEnumerabe<XElement>. The "OrderID" is actually a child element of each XElement.

Conducting some more research on this would probably be helpful. With the help of google search, my results show that the System.Linq.Dynamic library was not designed for use with XML.

See this SO Question where the OP concludes:

I finally got it working. I abandoned my original approach because as of now I'm not convinced it was even intended for use with Xml. I've seen little posted anywhere to argue against that statement.

What about reading the XML into a DataSet?

DataSet dataSet = new DataSet();

string sort = sortColumn + " " + OrderDirection;

DataTable table = dataSet.Tables["Orders"].Select("", sort)
                                          .Skip(lowerPageBoundary - 1 * rowsPerPage)

table.Locale = System.Globalization.CultureInfo.InvariantCulture;
5/23/2017 12:23:34 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow