What is an easy way to Format or Indent XML in an application? I know there are editors for doing it, but is there a simple method for doing this in an application? Yes there is; see the code here.
I have had several different applications where I want to display XML in an application and want it to be Indented or "Pretty Printed". The code shown below will show you how to easily display the XML string in an indented format. First, I need to create an application. I could create a Windows App and make a form and display the output in a TextBox, but to show you the meat of the formatting, I will keep it simple and create a console application.
In the following code snippets, I will display the whole application. The Main Sub will only create an unformatted XML string and pass it to the Indenting Function. Since I wrote my last article in VB.NET, I will code this one in C# just to keep my C# skills going. I am currently on a VB.NET Contract, so I take every opportunity I can to try to keep from getting rusty in C#.
| using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml; using System.Windows.Forms; namespace IndentXML { class Program { static void Main(string[] args) { string unformattedXml = "<People><Person><FirstName>John" + "<LastName>Doe<Person>" + "<FirstName>Mary<LastName>Doe" + ""; string formattedXML = IndentXMLString(unformattedXml); Console.WriteLine(formattedXML); } |
| private static string IndentXMLString(string xml) { string outXml = string.Empty; MemoryStream ms = new MemoryStream(); // Create a XMLTextWriter that will send its output to a memory stream (file) XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode); XmlDocument doc = new XmlDocument(); try { // Load the unformatted XML text string into an instance // of the XML Document Object Model (DOM) doc.LoadXml(xml); // Set the formatting property of the XML Text Writer to indented // the text writer is where the indenting will be performed xtw.Formatting = Formatting.Indented; // write dom xml to the xmltextwriter doc.WriteContentTo(xtw); // Flush the contents of the text writer // to the memory stream, which is simply a memory file xtw.Flush(); // set to start of the memory stream (file) ms.Seek(0, SeekOrigin.Begin); // create a reader to read the contents of // the memory stream (file) StreamReader sr = new StreamReader(ms); // return the formatted string to caller return sr.ReadToEnd(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return string.Empty; } } } } |
| <People> <Person> <FirstName>John</FirstName> <LastName>Doe</LastName> </Person> <Person> <FirstName>Mary</FirstName> <LastName>Doe</LastName> </Person> </People> |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |