all groups > dotnet xml > december 2003 >
You're in the

dotnet xml

group:

XPathDocument and retrieving xml string


XPathDocument and retrieving xml string Robert Strickland
12/27/2003 10:53:57 PM
dotnet xml:
I load an xml stream into a xpathdocument type, compile a xpath expression
and select to specific node. I find the node and wish to return the innerxml
of that node. When I use value of the current node I get back the "values"
of the child nodes but no formatted xml which I need for transformations
later in the sequence. Is there a way to pull pure xml from the
xpathdocument?

Re: XPathDocument and retrieving xml string Martin Honnen
12/28/2003 8:08:09 PM


[quoted text, click to view]

If you need access to the nodes as XmlNode objects then you need an
XmlDocument and not an XPathDocument, for instance try


using System;
using System.Xml;
using System.Xml.XPath;

public class Test20031228 {

public static void Main (string[] args) {
XPathDocument xpathDocument = new XPathDocument(@"test20031228.xml");
XPathNavigator xpathNavigator = xpathDocument.CreateNavigator();
TestXPathNavigator(xpathNavigator);

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"test20031228.xml");
xpathNavigator = xmlDocument.CreateNavigator();
TestXPathNavigator(xpathNavigator);
}

static void TestXPathNavigator (XPathNavigator xpathNavigator) {
XPathExpression xpathExpression = xpathNavigator.Compile("/*");
XPathNodeIterator nodeIterator =
xpathNavigator.Select(xpathExpression);
while (nodeIterator.MoveNext()) {
xpathNavigator = nodeIterator.Current;
IHasXmlNode hasXmlNode = xpathNavigator as IHasXmlNode;
if (hasXmlNode != null) {
XmlNode currentNode = hasXmlNode.GetNode();
Console.WriteLine(currentNode.InnerXml);
}
else {
Console.WriteLine("Can't access nodes.");
}
}
}

}

and you will find that the cast to IHasXmlNode (which has the GetNode
method) fails for the navigator created from the XPathDocument while it
works for the navigator created from the XmlDocument.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Re: XPathDocument and retrieving xml string Robert Strickland
12/28/2003 10:42:38 PM
Thanks

[quoted text, click to view]

AddThis Social Bookmark Button