2009-01-09 86 views
1

我有一个字符串中未格式化的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,是有可能实现什么,我想在这里做什么?

+0

什么是格式化的HTML字符串?例子会有所帮助。 – shahkalpesh 2009-01-09 04:39:09

回答

2

这里所做的正是这一个功能:

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

框架中没有什么能够做到你想要的。

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

2

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

0

使用EFTidyNet,为Tidy托管的.NET包装。这比使用批处理文件调用Tidy要简单得多,速度也要快很多。

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