我有一个 XPathDocument 并想将其导出为一个字符串,该字符串包含作为 XML 表示形式的文档。最简单的方法是什么?
最佳答案
您可以执行以下操作来获取 XML 文档的字符串表示形式:
XPathDocument xdoc = new XPathDocument(@"C:\samples\sampleDocument.xml");
string xml = xdoc.CreateNavigator().OuterXml;
如果您希望您的字符串包含 XML 文档的完整表示,包括 XML 声明,您可以使用以下代码:
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();
关于c# - 将 XPathDocument 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3510414/