Filter and sort XML before binding it to a repeater?
How I can filter, sort xml before binding it to a repeater? I have a xml data which I need to filter on the basis of querystring and then sort it before binding it into repeater.
I know how to bind xml with repeater and its working fine too but I am facing problem in filtering based on query string and sorting.
Any help would really be appreciated?
My XML is like this
<Categories>
<Category>
<Title>Food<Title>
<Date>12/1/2009</Date>
<Duration>12/1/2009-12/1/2011</Duration>
<Description>Who is hungry</Description>
<Category>
<Categories>
I want to sort by date and duration. I also want to filter by title (based on the querystr开发者_StackOverflowing).
LINQ to XML is probably the way to go here, but if you're stuck in 2.0-land, this will return an XPathNodeIterator
that provides your filtered and sorted XML:
// xPathFilter is a valid XPath expression
IEnumerable PrepareXml(XmlReader xmlReader, string xPathFilter)
{
XPathNavigator navigator = new XPathDocument(xmlReader).CreateNavigator();
// Compile is an XPathExpression factory method
XPathExpression expression = XPathExpression.Compile(xPathFilter);
// This sorts on the values of the selected nodes
// You might make an overload to let the caller specify different comparers
expression.AddSort(".", StringComparer.CurrentCulture);
return navigator.Select(expression);
}
Note that if you only needed to filter (not sort), you could use the simpler, declarative TemplateControl.XPathSelect
right in your aspx template (the example in the linked documentation is pretty close to your scenario).
XPathNodeIterator
implements IEnumerable
, so you can bind a repeater directly to it. To get values in child nodes, use the TemplateControl.XPath
method, like this (you could also get attributes or grand-child nodes, etc., with appropriate XPath expressions):
<ItemTemplate>
We have <%# XPath("Title") %> available starting on <%# XPath("Date") %>:<br />
<%# XPath("Description") %>
</ItemTemplate>
I would use the built-in capabilities of LINQ to XML to handle filtering & sorting. Here is a link to do complex filtering. Here is one that shows how to do simple sorting.
Combine the two techniques and instead of binding the control to an XML data source, bind to the resulting collection from the final LINQ to XML processing.
For some good LINQ to XML samples go here
精彩评论