如何以编程方式格式化HTML字符串

时间:2009-01-09 04:27:01

标签: .net .net-2.0

我在字符串中输入了未格式化的HTML。

我正在尝试将其格式化并将格式化的html输出回字符串。 我一直在尝试使用System.Web.UI.HtmlTextWriter无济于事:

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

我得到的只是未格式化的HTML,是否有可能实现我在这里尝试做的事情?

4 个答案:

答案 0 :(得分:3)

这是一个完全符合这个功能的函数:

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

答案 1 :(得分:2)

如果您愿意使用XHTML而不是HTML,可以在外部将其传递给tidy或使用XmlTextWriter

答案 2 :(得分:0)

框架中没有任何内容能够满足您的需求。

如果HTML片段是有效的XML,您可以将其加载到XmlDocument中并编写一些代码来遍历它并按照您想要的格式输出它。

答案 3 :(得分:0)

使用EFTidyNet,Tidy的托管.NET包装器。它比使用批处理文件调用Tidy简单得多,而且速度也快得多。

Tidy可以清理您的HTML并使其看起来不错,并将其转换为有效的HTML或XHTML。