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 contains the selected nodes only?
}
The
XPathNodeIteratordoes 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 originalbaseXMLobject 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, callImportNodeand thenAppend. This will create a flat XmlDocument with all the selected nodes in the root element.