LINQ to XML Newbie Question: Reading xml and Ordering by Attribute

I have a noob LINQ to XML question. I have this xml:

<pages>
    <page Name="Welcome" Control="Welcome" Order="1"></page>
    <page Name="Summary" Control="Summary" Order="10"></page>
</pages>

      

I need to read the data and store it in an array, ordered by the "Order" attribute. Here's what I have; the compiler coughs in order according to the sentence.

//read in app.xml data into _Pages
XDocument doc = XDocument.Parse("app.xml");
XElement Pages = (XElement)doc.Descendants("pages");

var Pages1 =
  (from page in Pages  //<-- error on orderby clause
  orderby page.order
  select page).ToArray();

      

I searched SO and found several LINQ to XML answers similar to this, but will say something about an xml fragment in a Pages object. But never show it.

thank

EDIT: Error: Could not find a query pattern implementation for source type "System.Xml.Linq.XElement". "OrderBy" was not found.

+2


source to share


2 answers


I assume you want something like this:

using System.Linq;
using System.Xml.Linq;
namespace SampleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = @"<pages>   
                <page Name=""Summary"" Control=""Summary"" Order=""10""></page> 
                <page Name=""Welcome"" Control=""Welcome"" Order=""1""></page>
            </pages>";
            XDocument doc = XDocument.Parse(xml);
            XElement[] pages = doc
              .Descendants("page")
              .OrderBy(x => (int)x.Attribute("Order"))
              .ToArray();
        }
    }
}

      



Does this work for you? This works by making sure the Order attribute is always int (I made an assumption here).

+4


source


Try "Attribute" ("order") instead of page.order.



+1


source







All Articles