C# 格式化输出XML

很多时候有一个xml字符串,没有换行,没有缩进,要生成xml文件不易阅读。下面的代码就是怎么将一个连续的xml字符串格式化输出

// a demo string
string xml = "<Root><Eles><Ele>abc</Ele><Ele>123</Ele></Eles></Root>";

System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xml);

System.IO.StringWriter sw = new System.IO.StringWriter();
using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
{
    writer.Indentation = 2;  // the Indentation
   
writer.Formatting = System.Xml.Formatting.Indented;
    doc.WriteContentTo(writer);
    writer.Close();
}

// out put the formated xml
Console.WriteLine(sw.ToString());

猜你喜欢

转载自blog.csdn.net/superyoungchaos/article/details/5182136