I have an XPathDocument and would like to export it in a string that contains the document as XML representation. What is easiest way of doing so?
+2
A:
You can do the following to get a string representation of the XML document:
XPathDocument xdoc = new XPathDocument(@"C:\samples\sampleDocument.xml");
string xml = xdoc.CreateNavigator().OuterXml;
If you want your string to contain a full representation of the XML document including an XML declaration you can use the following code:
XPathDocument xdoc = new XPathDocument(@"C:\samples\sampleDocument.xml");
StringBuilder sb = new StringBuilder();
using (XmlWriter xmlWriter = XmlWriter.Create(sb))
{
xdoc.CreateNavigator().WriteSubtree(xmlWriter);
}
string xml = sb.ToString();
0xA3
2010-08-18 09:01:30
A:
An XPathDocument
is a read-only representation of an XML document. That means that the internal representation will not change. To get the XML, you can get the original document.
Or use 0xA3's method, which will go through the whole document and write it again (output not necessarily the same as input, yet structurally and functionally equal, because some input is discarded with XDM in-memory representation)
Abel
2010-08-18 09:04:29