Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a string of HTML programatically

Tags:

.net

.net-2.0

I've got unformatted html in a string.

I am trying to format it nicely and output the formatted html back into a string. I've been trying to use The System.Web.UI.HtmlTextWriter to no avail:

System.IO.StringWriter wString = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter wHtml = new System.Web.UI.HtmlTextWriter(wString);

wHtml.Write(sMyUnformattedHtml);

string sMyFormattedHtml = wString.ToString();

All I get is the unformatted html, is it possible to achieve what I'm trying to do here?

like image 965
Jeremy Avatar asked Oct 13 '25 02:10

Jeremy


2 Answers

Here's a function that does exactly that:

    // Attractively format the XML with consistant indentation.

    public static String PrettyPrint(String XML)
    {
        String Result = "";

        using (MemoryStream MS = new MemoryStream())
        {
            using (XmlTextWriter W = new XmlTextWriter(MS, Encoding.Unicode))
            {
                XmlDocument D = new XmlDocument();

                try
                {
                    // Load the XmlDocument with the XML.
                    D.LoadXml(XML);

                    W.Formatting = Formatting.Indented;

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

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

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

                    // Extract the text from the StreamReader.
                    String FormattedXML = SR.ReadToEnd();

                    Result = FormattedXML;
                }
                catch (XmlException ex)
                {
                    Result= ex.ToString();
                }

                W.Close();
            }
            MS.Close();
        }
        Debug.WriteLine(Result);
        return Result;
    }
like image 146
lotsoffreetime Avatar answered Oct 14 '25 23:10

lotsoffreetime


You can pass it to tidy externally or use XmlTextWriter if you are willing to use XHTML instead of HTML.

like image 35
Eugene Yokota Avatar answered Oct 14 '25 23:10

Eugene Yokota