Friday, January 14, 2011

XML Programatically make xml tags look aligned

The next code is useful for making your XML tags a little more readable by aligning the tags.



public static String xmlAligned(String Xml)
        {
            String Result = Xml;
            if (Xml.Length != 0)
            {
                try
                {
                    // Load the XmlDocument with the XML variable
                    XmlDocument D = new XmlDocument();
                    D.LoadXml(Xml);
                    MemoryStream MS = new MemoryStream();
                    XmlTextWriter W = new XmlTextWriter(MS, System.Text.Encoding.Unicode);

                    // Format the XML document
                    W.Formatting = Formatting.Indented;

                    // Write the Xml into a formatting XmlTextWriter
                    D.WriteContentTo(W);
                    W.Flush();
                    MS.Flush();

                    // Rewind the MemoryStream in order to read its contents.
                    MS.Position = 0;

                    // Read MemoryStream contents
                    StreamReader SR = new StreamReader(MS);

                    // Get the text
                    String FormattedXml = SR.ReadToEnd();

                    // Get the results
                    Result = FormattedXml;

                    try
                    {
                        // Close all the resources used
                        MS.Close();
                        MS = null;
                        W.Close();
                        W = null;
                    }
                    catch { }
                }
                catch { }
            }

            // Return the aligned XML
            return Result;
        }



No comments:

Post a Comment