Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XPathDocument to string

Tags:

c#

xml

xpath

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?

like image 330
koumides Avatar asked Dec 09 '22 14:12

koumides


1 Answers

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();
like image 80
Dirk Vollmar Avatar answered Dec 24 '22 14:12

Dirk Vollmar