Returns formatted xml string (indent and newlines) from unformatted XML - CSharp System.Xml

CSharp examples for System.Xml:XML String

Description

Returns formatted xml string (indent and newlines) from unformatted XML

Demo Code


using System.Globalization;
using System.Security.Cryptography;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Collections;
using System.Xml.XPath;
using System.Text;
using System.Xml;
using System.IO;// w  w w  .j  a va  2  s.c o m
using System;

public class Main{
        /// <summary>
      /// Returns formatted xml string (indent and newlines) from unformatted XML
      /// </summary>
      /// <param name="sUnformattedXml">Unformatted xml string.</param>
      /// <returns>Formatted xml string and any exceptions that occur.</returns>
      public static string FormatXml(string sUnformattedXml)
      {
         XmlDocument xd = new XmlDocument();
         xd.LoadXml(sUnformattedXml);
         StringBuilder sb = new StringBuilder();
         StringWriter sw = new StringWriter(sb);

         XmlTextWriter xtw = null;
         try
         {
            xtw = new XmlTextWriter(sw);
            xtw.Formatting = Formatting.Indented;
            xd.WriteTo(xtw);
         }
         finally
         {
            //clean up even if error
            if (xtw != null)
               xtw.Close();
         }

         return sb.ToString();
      }
}

Related Tutorials