Reading XML – the XPath-way

So I though I’ll be a smartass and upgrade my code-usage of XmlDocument to IXpathNavigable. So far everything is working just fine!

So previously I did something like this:

string myXml = "<query><where field='name'>foo</where></query>";
XmlDocument myDoc = new XmlDocument();
myDoc.LoadXml(myXml);
return myDoc.SelectSingleNode("//query").InnerXml;

This would get my the inner XML which could further be used.

Changing to the XPath-model introduced with .Net 2.0 this would look like this:

string myXml = "<query><where field='name'>foo</where></query>";
XPathDocument myPath;
using (StringReader sr = new StringReader(myXml))
myPath = new XPathDocument(sr);
return myPath.CreateNavigator().SelectSingleNode("//query").InnerXml;

However, this will not return my inital myXml string but instead a /pretty printed/ version of the xml string. This however is not a string that can be parsed as a xml object because of the \r\n in the string.

So instead of the SelectSingleNode I tried something else:

string myXml = "<query><where field='name'>foo</where></query>";
XPathDocument myPath;
using (StringReader sr = new StringReader(myXml))
myPath = new XPathDocument(sr);
using (XmlReader xr = myPath.CreateNavigator().ReadSubtree())
return xr.ReadInnerXml();

But oddly, this will always return an empty string, and the XmlReader is always none.

Until I figured this:

string myXml = "<query><where field='name'>foo</where></query>";
XPathDocument myPath;
using (StringReader sr = new StringReader(myXml))
myPath = new XPathDocument(sr);
using (XmlReader xr = myPath.CreateNavigator().ReadSubtree())
{
xr.Read();
return xr.ReadInnerXml();
}

The Read() of the XmlReader sets the reader from the initializing state into reading state … and now ReadInnerXml() actually contains my xml string, without any nasty \r\n.