This is the fourth post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .
You can find the third post here .
The xml file we are going to use in all these posts is the students.xml file. You can find the contents of this xml file in the first post.
I
will use Visual Studio 2010 Ultimate edition and C# as the development
language. Visual Studio 2010/2008 express editions will suffice.
In this fourth post I will look at how to "How to sort elements with an xml file using LINQ to XML".
In this post we want to sort the elements in the students.xml document according to City in a descending order.
1) Fire VS and create a web site. Choose an appropriate name for your site.
2) Add the existing students.xml file in your website.
3) In the code behind file Default.aspx.cs, add the namespace
using System.Xml.Linq;
All the classes we need to manipulate XML documents are inside this namespace.
In the Page_Load event handling routine of the default.aspx.cs file, type the following
XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");
var cities = from thecity in xelement.Elements("Student")
let city = (string)thecity.Element("Address").Element("City")
orderby city descending
select city;
Response.Write("Sort all cities descending: ");
Response.Write("<br/>");
foreach (string mycity in cities)
{
Response.Write(mycity);
Response.Write("<br/>");
}
4) In our LINQ to XML query we see how easy is to sort using the order by clause.
let city = (string)thecity.Element("Address").Element("City")
orderby city descending
5) Run your application and see in the browser the following results.
Sort all cities ascending:
Milano
Livorno
Edinburgh
Athens