How to sort an XML using XPathExpression?
If you want to sort a XML document you have two options (at least these are the two options I know). The first would be to pass a sort parameter to the XSLT and the XSLT would do the sorting for us. The second one would be to use the XPathExpression class which provides a function called AddSort. This function does the sorting for us. This how to shows the second option!
Used Classes:
XPathDocument
XPathExpression
XPathNavigator
XPathNodeIterator
XML File:
<?xml version="1.0" encoding="utf-8"?>
<CategoryList>
<Category ID="01">
<Title>One</Title>
</Category>
<Category ID="03">
<Title>Three</Title>
</Category>
<Category ID="04">
<Title>Four</Title>
</Category>
<Category ID="02">
<Title>Two</Title>
</Category>
</CategoryList>
Code:
XPathDocument xpathDoc = new XPathDocument(Server.MapPath("categories.xml"));
XPathNavigator nav = xpathDoc.CreateNavigator();
XPathExpression expr;
expr = nav.Compile("CategoryList/Category");
//Sort Category by ID.
expr.AddSort("@ID", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Text);
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext()){
Response.Write("Attribute = ");
Response.Write(iterator.Current.GetAttribute("ID",""));
Response.Write(" Title = ");
Response.Write(iterator.Current.Value);
Response.Write("<br>");
}
Output:
Attribute = 01 Title = One
Attribute = 02 Title = Two
Attribute = 03 Title = Three
Attribute = 04 Title = Four