In C#, how do I convert a XmlNode to string, with indentation? (Without looping)

ぐ巨炮叔叔 提交于 2019-12-05 00:00:49
drharris

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()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!