Archives

  • Categories

  • Formatting an Xml String

    Here is a useful bit of code for formatting a piece of xml as a string with all those nice indents..I find it useful when i have to log messages etc..

    public static class XmlStringFormatter
        {
            ///
    
            /// Returns formatted xml string (indent and newlines) from unformatted XML
            /// string for display in eg textboxes.
            /// 
    
            ///
    Unformatted xml string.
            /// Formatted xml string and any exceptions that occur.
            public static string FormatXml(this string unformattedXml)
            {
                //load unformatted xml into a dom
                var xd = new XmlDocument();
                xd.LoadXml(unformattedXml);
    
                //will hold formatted xml
                var sb = new StringBuilder();
    
                //pumps the formatted xml into the StringBuilder above
                var sw = new StringWriter(sb);
    
                //does the formatting
                XmlTextWriter xtw = null;
    
                try
                {
                    //point the xtw at the StringWriter
                    xtw = new XmlTextWriter(sw) {Formatting = Formatting.Indented};
    
                    //we want the output formatted
                    //get the dom to dump its contents into the xtw
                    xd.WriteTo(xtw);
                }
                finally
                {
                    //clean up even if error
                    if (xtw != null)
                        xtw.Close();
                }
    
                //return the formatted xml
                return sb.ToString();
            }
        }
    

    Leave a Reply