开发者

Returning an XmlDocument from XPathNodeIterator

I need some help in returning an XmlDocument object from XPathNodeIterator.

Here is what I was trying to do:

public XmlDocument GetFilteredXML(XmlDocument baseXML, int codeID)
{
    XPathNavigator nav = baseXML.CreateNavigator();
    string xpath = /*some expression based on codeID*/;
    XPathExpression exp = nav.Compile(xpath);
    exp.AddSort(/*do some sorting*/);
    XPathNodeIterator iter = exp.Select(exp);

    // Here how do I return an XmlDocument object from
    // the iterator which con开发者_如何学编程tains the selected nodes only?
}


The XPathNodeIterator does not contain the nodes, exactly. The name is a clue - it is an iterator, which means it only contains the logic for how to iterate over the nodes you want. The nodes themselves come from somewhere else - in this case, the original baseXML object you provided. They never leave that object, you just created a navigator that knows how to navigate the document, and an iterator, which knows how to iterate the navigator using some criteria.

To do what you're describing, you need to create a new XmlDocument, give it a new root element, and for each node from the iterator, call ImportNode and then Append. This will create a flat XmlDocument with all the selected nodes in the root element.


This is an option:

if (iter.MoveNext())  // Position on first node selected,
{                     // assuming that it is the container for the desired result.
    XmlDocument output = new XmlDocument();
    output.LoadXml(iter.Current.OuterXml);
    return output;
}

However, I don't think you need to make it into an XPathNavigator in the first place. What operation are you doing, that cannot be accomplished using the XmlDocument methods ?(SelectNodes and SelectSingleNode springs to mind for evaluating an XPath expression)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜