XPathNodeIterator get outerXml?

  • Thread starter Thread starter KJ
  • Start date Start date
K

KJ

It is true that there is no way to get the outerXml of
XPathNodeIterator.Current? Please say it isn't so.
 
KJ said:
It is true that there is no way to get the outerXml of
XPathNodeIterator.Current? Please say it isn't so.

That depends on the type of document you have created the XPathNavigator
over, if it is an XmlDocument then you can do it:

XmlDocument doc = new XmlDocument();
doc.Load("books.xml");

// Create an XPathNavigator and select all books by Plato.
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator ni =
nav.Select("descendant::book[author/name='Plato']");
ni.MoveNext();

// Get the first matching node
XmlNode book = ((IHasXmlNode)ni.Current).GetNode();
Console.WriteLine(book.OuterXml);

But that cast to IHasXmlNode will fail for an navigator created over an
XPathDocument.
 
It depends. XPathNodeIterator.Current returns an XPathNavigator
instance represented by the current node within the iteration.
XPathNavigator is an abstract class and by itself does not provide
OuterXml support.

However, one of the implementation sof XPathNavigator is
DocumentXPathNavigator which implements IHasXmlNode which expose
GetNode() which returns the corresponding XmlNode instance. This does
have an OuterXml property.

So to conditionally get OuterXml you can do something like

XPathNavigator current = iterator.Current;
string outerXml;

if (current != null && current is IHasXmlNode) {
outerXml = ((IHasXmlNode)current).GetNode().OuterXml;
} else {
outerXml = "<unavailable>";
}

Whether or not the XPathNavigator implementation is a
DocumentXPathNavigator or something else depends on what the
XPathNodeIterator is iterating over in the first place--if it
originally came from an XmlDocument then it will be
DocumentXPathNavigator, but if you're iterating something else, then
the current node implementation will be different.

HTH,

Sam
 
Back
Top