[C#] Format a XML string using XmlTextWriter

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

 

From: http://jack-fx.com

posted on 2009-05-09 10:48  Jack Niu  阅读(1292)  评论(0编辑  收藏  举报

Affiliate Marketing and Web Technology