KnowDotNet

Easy Way to Indent XML in a TextBox

Working With XML

by Les Smith

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);
      }


Now for the code to do the actual formatting of the XML, I will write a function called IndentXMLString.  It will format the string passed as a parameter and return the Indented/Formatted XML String.

      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;
         }
      }
   }
}


In the Main Sub, set a breakpoint on the End Sub line and then you can see the contents of the Output Window and it will look as shown below.

<People>
  <Person>
    <FirstName>John</FirstName>
    <LastName>Doe</LastName>
  </Person>
  <Person>
    <FirstName>Mary</FirstName>
    <LastName>Doe</LastName>
  </Person>
</People>


Some complex things that we would try to do before the .NET Framework was created have been made so simple by the .NET Framework.  With this code snippet and a little ingenuity, it would not take much to create your own home grown XML Editor.

Have you tried our newest product, Visual Class Organizer?  You'll be amazed how easy it is to keep the code in your code windows organized.  TRY IT FREE FOR 30 DAYS BY CLICKING HERE.



If you are developing in C# and haven't tried CSharpCompleter, you are wasting valuable time typing hundreds of braces {} daily needlessly.  Try CSharpCompleter for 30 DAYS FREE.



Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog.