Linq to XML & ASP.Net - part 4
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 . 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". 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 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 followingusing System.Xml.Linq;
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 descending5) Run your application and see in the browser the following results.
Sort all cities ascending:
Milano
Livorno
Edinburgh
Athens