I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there\'s a pub
Assuming your're simply wanting to re-format an XML document to put new nodes on new lines and add indenting, then, if you are using .NET 3.5 or above then the best solution is to parse then output with XDocument, somthing like:
string unformattedXml;
string formattedXml;
unformattedXml = "Lewis, C.S. The Four Loves ";
formattedXml = System.Xml.Linq.XDocument.Parse(unformattedXml).ToString();
Console.WriteLine(formattedXml);
Neat hu?
This should then re-format the XML nodes.
To do this with previous versions of the framework requires a lot more legwork as there is no built in functions to re-calculate the whitespace.
In fact, to do it using pre-Linq classes would be:
string unformattedXml;
string formattedXml;
unformattedXml = "Lewis, C.S. The Four Loves ";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(unformattedXml);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb, new System.Xml.XmlWriterSettings() { Indent = true });
doc.WriteTo(xw);
xw.Flush();
formattedXml = sb.ToString();
Console.WriteLine(formattedXml);