开发者

Convert XPathDocument to string

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?


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();


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜