Chad
Chad

Reputation: 912

LINQ to XML Newbie Question: Reading xml and order by attribute

I have a noob LINQ to XML question. I have xml like so:

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

I need to read in the data and save it to an array ordered by the "Order" attribute. Here's what I have; the compiler is coughing on the order by clause.

//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've search SO and found several LINQ to XML answers looking like this, but say something about the xml fragment in an object like Pages. But never show it's type.

Thanks

EDIT: The error is: Could not find an implementation of the query pattern for source type 'System.Xml.Linq.XElement'. 'OrderBy' not found.

Upvotes: 2

Views: 4893

Answers (2)

RichardOD
RichardOD

Reputation: 29157

I'm guessing 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 that work for you? This works providing the Order attribute is always an int (I have made an assumption here).

Upvotes: 4

Matt Wrock
Matt Wrock

Reputation: 6640

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

Upvotes: 1

Related Questions