在C#中写入HTML

我有这样的代码。 有没有办法让写和维护更容易? 使用C#.NET 3.5

string header(string title) { StringWriter s = new StringWriter(); s.WriteLine("{0}","<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"); s.WriteLine("{0}", "<html>"); s.WriteLine("<title>{0}</title>", title); s.WriteLine("{0}","<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">"); s.WriteLine("{0}", "</head>"); s.WriteLine("{0}", "<body>"); s.WriteLine("{0}", ""); } 

– 编辑 – 我不知道,但我可以写

 s.WriteLine("{0}", @"blah blah many new lines blah UHY#$&_#$_*@Y KSDSD<>\t\t\t\t\t\tt\t\t\\\t\t\t\t\\\h\th'\h't\th hi done"); 

它将工作,但需要取代所有“与”“

使用HtmlTextWriterXMLWriter比使用纯StringWriter更好。 他们会照顾你的逃跑,以及确保文件格式正确。

该页面显示了使用HtmlTextWriter类的基础知识,其要点是:

 using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter)) { writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue); writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1 writer.AddAttribute(HtmlTextWriterAttribute.Href, urlValue); writer.RenderBeginTag(HtmlTextWriterTag.A); // Begin #2 writer.AddAttribute(HtmlTextWriterAttribute.Src, imageValue); writer.AddAttribute(HtmlTextWriterAttribute.Width, "60"); writer.AddAttribute(HtmlTextWriterAttribute.Height, "60"); writer.AddAttribute(HtmlTextWriterAttribute.Alt, ""); writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3 writer.RenderEndTag(); // End #3 writer.Write(word); writer.RenderEndTag(); // End #2 writer.RenderEndTag(); // End #1 } // Return the result. return stringWriter.ToString(); 

当我用其他语言处理这个问题时,我会去分离代码和HTML。 就像是:

1.)创build一个HTML模板。 使用[varname]占位符标记replace/插入的内容。
2.)从数组或结构/映射/字典中填充模板variables

 Write( FillTemplate(myHTMLTemplate, myVariables) ) # pseudo-code 

我知道你问了C#,但是如果你愿意使用任何.Net语言,那么我强烈build议Visual Basic解决这个问题。 Visual Basic有一个名为XML Literals的function,可以让你编写这样的代码。

 Module Module1 Sub Main() Dim myTitle = "Hello HTML" Dim myHTML = <html> <head> <title><%= myTitle %></title> </head> <body> <h1>Welcome</h1> <table> <tr><th>ID</th><th>Name</th></tr> <tr><td>1</td><td>CouldBeAVariable</td></tr> </table> </body> </html> Console.WriteLine(myHTML) End Sub End Module 

这使您可以在旧的ASP风格中编写带有expression孔的直接HTML,并使您的代码超级可读。 不幸的是,这个function不是用C#编写的,但是你可以在VB中编写一个单独的模块,并将其添加为C#项目的参考。

在Visual Studio中编写也允许大多数XML文字和expression式整体的正确缩进。 VS2010中expression式的缩进比较好。

 return string.Format(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http://www.w3.org/TR/html4/strict.dtd""> <html> <title>{0}</title> <link rel=""stylesheet"" type=""text/css"" href=""style.css""> </head> <body> ", title); 

您可以使用T4模板从代码生成Html(或任何)。 看到这个: http : //msdn.microsoft.com/en-us/library/ee844259.aspx

使用XDocument创buildDOM,然后使用XmlWriter将其写出。 这将给你一个非常简洁和可读的记法,以及格式良好的输出。

拿这个示例程序:

 using System.Xml; using System.Xml.Linq; class Program { static void Main() { var xDocument = new XDocument( new XDocumentType("html", null, null, null), new XElement("html", new XElement("head"), new XElement("body", new XElement("p", "This paragraph contains ", new XElement("b", "bold"), " text." ), new XElement("p", "This paragraph has just plain text." ) ) ) ); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true, IndentChars = "\t" }; using (var writer = XmlWriter.Create(@"C:\Users\wolf\Desktop\test.html", settings)) { xDocument.WriteTo(writer); } } } 

这将生成以下输出:

 <!DOCTYPE html > <html> <head /> <body> <p>This paragraph contains <b>bold</b> text.</p> <p>This paragraph has just plain text.</p> </body> </html> 

你可以使用System.Xml.Linq对象。 他们完全从旧的System.Xml时代重新devise,从头开始构buildXML真的很烦人。

除了我猜的文档types,你可以很容易地做这样的事情:

 var html = new XElement("html", new XElement("head", new XElement("title", "My Page") ), new XElement("body", "this is some text" ) ); 

最直接的方法是使用XmlWriter对象。 这可以用来生成有效的HTML,并将为您处理所有讨厌的转义序列。

如果您希望创build一个类似于在C#中创buildXML文档的HTML文档,您可以尝试一下微软的开源库Html Agility Pack 。

它提供了一个HtmlDocument对象,它具有与System.Xml.XmlDocument类非常相似的API。

您可以使用ASP.NET在网页上下文之外生成HTML。 这里有一篇文章展示了如何完成。

您可以使用一些第三方开源库来生成强typesvalidation(X)HTML,如CityLizard Framework或Sharp DOM。

更新例如

 html [head [title["Title of the page"]] [meta_( content: "text/html;charset=UTF-8", http_equiv: "Content-Type") ] [link_(href: "css/style.css", rel: "stylesheet", type: "text/css")] [script_(type: "text/javascript", src: "/JavaScript/jquery-1.4.2.min.js")] ] [body [div [h1["Test Form to Test"]] [form_(action: "post", id: "Form1") [div [label["Parameter"]] [input_(type: "text", value: "Enter value")] [input_(type: "submit", value: "Submit!")] ] ] [div [p["Textual description of the footer"]] [a_(href: "http://google.com/") [span["You can find us here"]] ] [div["Another nested container"]] ] ] ]; 

这不是一个通用的解决scheme,但是,如果你的目的是拥有或维护电子邮件模板,那么System.Web有一个名为MailDefinition的内置类。 ASP.NET会员控件使用此类创buildHTML电子邮件。

上面提到的是同一种“stringreplace”的东西,但把它们全部包装成一个MailMessage给你。

这里是一个来自MSDN的例子:

 ListDictionary replacements = new ListDictionary(); replacements.Add("<%To%>",sourceTo.Text); replacements.Add("<%From%>", md.From); System.Net.Mail.MailMessage fileMsg; fileMsg = md.CreateMailMessage(toAddresses, replacements, emailTemplate, this); return fileMsg; 

你可以用自己的Render方法编写自己的类,也可以使用其他属性,如果你使用它的话,可以避免太大的混乱,然后使用HTMLWriter或者xmlwriter。 这个逻辑用在asp.net页面中,你可以从webControlinheritance并重写render方法 ,如果你正在开发服务器端的控件,那就太棒了。
这可能是一个很好的例子。

问候

这真的取决于你要做什么,特别是你真正需要提供什么样的performance。

对于强types的HTML开发(完整的控件模型,无论是ASP.NET Web控件还是类似的),我已经看到了令人赞叹的解决scheme,这些解决scheme为项目增添了惊人的复杂性。 在其他情况下,这是完美的。

按照C#世界的偏好顺序,

  • ASP.NET Web控件
  • ASP.NET基元和HTML控件
  • XmlWriter和/或HtmlWriter
  • 如果使用HTML互操作性进行Silverlight开发,请考虑强types的链接文本
  • StringBuilder等超级原语

我写了这些课程给我很好的服务。 它简单而实用。

 public class HtmlAttribute { public string Name { get; set; } public string Value { get; set; } public HtmlAttribute(string name) : this(name, null) { } public HtmlAttribute( string name, string @value) { this.Name = name; this.Value = @value; } public override string ToString() { if (string.IsNullOrEmpty(this.Value)) return this.Name; if (this.Value.Contains('"')) return string.Format("{0}='{1}'", this.Name, this.Value); return string.Format("{0}=\"{1}\"", this.Name, this.Value); } } public class HtmlElement { protected List<HtmlAttribute> Attributes { get; set; } protected List<object> Childs { get; set; } public string Name { get; set; } protected HtmlElement Parent { get; set; } public HtmlElement() : this(null) { } public HtmlElement(string name, params object[] childs) { this.Name = name; this.Attributes = new List<HtmlAttribute>(); this.Childs = new List<object>(); if (childs != null && childs.Length > 0) { foreach (var c in childs) { Add(c); } } } public void Add(object o) { var a = o as HtmlAttribute; if (a != null) this.Attributes.Add(a); else { var h = o as HtmlElement; if (h != null && !string.IsNullOrEmpty(this.Name)) { h.Parent = this; this.Childs.Add(h); } else this.Childs.Add(o); } } public override string ToString() { var result = new StringBuilder(); if (!string.IsNullOrEmpty(this.Name)) { result.Append(string.Format("<{0}", this.Name)); if (this.Attributes.Count > 0) { result.Append(" "); foreach (var attr in this.Attributes) { result.Append(attr.ToString()); result.Append(" "); } result = new StringBuilder(result.ToString().TrimEnd(' ')); } if (this.Childs.Count == 0) { result.Append(" />"); } else { result.AppendLine(">"); foreach (var c in this.Childs) { var cParts = c.ToString().Split('\n'); foreach (var p in cParts) { result.AppendLine(string.Format("{0}", p)); } } result.Append(string.Format("</{0}>", this.Name)); } } else { foreach (var c in this.Childs) { var cParts = c.ToString().Split('\n'); foreach (var p in cParts) { result.AppendLine(string.Format("{0}", p)); } } } var head = GetHeading(this); var ps = result.ToString().Split('\n'); return string.Join("\r\n", (from p in ps select head + p.TrimEnd('\r')).ToArray()); } string GetHeading(HtmlElement h) { if (h.Parent != null) return " "; else return string.Empty; } } 

HSharp是一个用来分析HTML等标记语言的库,方便快捷。 安装: PM> Install-Package Obisoft.HSharp

  var Document = new HDoc(DocumentOptions.BasicHTML); Document["html"]["body"].AddChild("div"); Document["html"]["body"]["div"].AddChild("a", new HProp("href", "/#")); Document["html"]["body"]["div"].AddChild("table"); Document["html"]["body"]["div"]["table"].AddChildren( new HTag("tr"), new HTag("tr", "SomeText"), new HTag("tr", new HTag("td"))); var Result = Document.GenerateHTML(); Console.WriteLine(Result); 

和输出:

 <html> <head> <meta charset="utf-8"></meta><title> Example </title> </head> <body> <div> <a href="/#"></a><table> <tr></tr><tr> SomeText </tr> <tr> <td></td></tr> </table> </div> </body> </html>