开发者

Sorting xmlnodelist with XPATH, and convert back to xmlnodelist

I have an xmlnodelist in C# I would like sort by ID without creating arrays. The XML data is loaded into a dynamic table I've created. I haven't studied a lot XPATH but I figured out by Googling the attached code co开发者_StackOverflow中文版uld work. Howevern, I would like to get the sorted output back as an xmlnodelist in order to create the dynamic table easily. Is this possible?

(http://forums.asp.net/t/1226980.aspx):

public partial class DefaultSamePage : System.Web.UI.Page
{
//a public var XmlNodeList, in order to use it both in sortNodeList and another function
    XmlNodeList sortedNodes;
}

   void sortNodeList()
{
        XPathDocument myQuiz = new XPathDocument(Server.MapPath("quiz.xml"));
        XPathNavigator nav = myQuiz.CreateNavigator();
        XPathExpression myExp = nav.Compile("//question");
        myExp.AddSort("@id", XmlSortOrder.Descending, XmlCaseOrder.None, "", XmlDataType.Number);
        XPathNodeIterator iter = nav.Select(myExp);
        while (iter.MoveNext())
        {
            // is this possible?
            sortedNodes = iter.Current.Value;

        }
}


However, I would like to get the sorted output back as an XmlNodeList in order to create the dynamic table easily

You can't. In order to have an XmlNodeList, you need XmlNodes, and an XmlNode has to belong to an XmlDocument. And you're not creating an XmlDocument.

Sort of the whole point of the XPathDocument that it doesn't create XmlNode objects. The reason to write code that uses IXPathNavigable is that if you have to navigate through tens of thousands of nodes to find six of them, your code doesn't have to create tens of thousands of XmlNode objects first. That's the main reason why XPathNavigator code is much faster than code that uses XmlDocument.

If you're going to use IXPathNagivable anywhere in your code, you should be using it everywhere. Don't write methods that take XmlNode and XmlNodeList as parameters; write methods that take XPathNavigator and XPathNodeIterator instead.

For instance, if you're populating a table from XML data, you might presently have methods that look like:

public DataTable PopulateTable(DataTable t, XmlNodeList nodes)
{
   foreach (XmlNode n in nodes)
   {
      CreateRow(t, n);
   }
}

private void CreateRow(DataTable t, XmlNode n)
{
   DataRow r = t.NewRow();
   t["foo"] = n.GetAttribute("foo");
   t["bar"] = n.GetAttribute("bar");
   t.Rows.Add(r);
}

You could just as easily write that code this way:

public void PopulateTable(DataTable t, XPathNodeIterator iter)
{
   foreach (XPathNavigator n in iter)
   {
      CreateRow(t, n);
   }
}

private void CreateRow(DataTable t, XPathNavigator n)
{
   DataRow r = t.NewRow();
   t["foo"] = n.GetAttribute("foo", "");
   t["bar"] = n.GetAttribute("bar", "");
   t.Rows.Add(r);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜