In C#, how do I convert a XmlNode to string, with indentation? (Without looping)
You were on the right path with the XMLTextWriter
, you simply need to use a StringWriter
as the base stream. Here are a few good answers on how this is accomplished. Pay particular attention to the second answer, if your encoding needs to be UTF-8.
Edit:
If you need to do this in multiple places, it is trivial to write an extension method to overload a ToString()
on XmlNode
:
public static class MyExtensions
{
public static string ToString(this System.Xml.XmlNode node, int indentation)
{
using (var sw = new System.IO.StringWriter())
{
using (var xw = new System.Xml.XmlTextWriter(sw))
{
xw.Formatting = System.Xml.Formatting.Indented;
xw.Indentation = indentation;
node.WriteContentTo(xw);
}
return sw.ToString();
}
}
}
If you don't care about memory or performance, the simplest thing is:
XElement.Parse(xmlNode.OuterXml).ToString()