C# 将 HTML 写入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1004776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:19:17  来源:igfitidea点击:

Write HTML to string

c#html

提问by

I have code like this. Is there a way to make it easier to write and maintain? Using C# .NET 3.5.

我有这样的代码。有没有办法让它更容易编写和维护?使用 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}", "");
}

I could also just write:

我也可以写:

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

It will work, but I need to replace all "with "".

它会起作用,但我需要将所有内容替换""".

回答by lc.

You're probably better off using an HtmlTextWriteror an XMLWriterthan a plain StringWriter. They will take care of escaping for you, as well as making sure the document is well-formed.

使用 anHtmlTextWriter或 an 可能XMLWriter比使用普通StringWriter. 他们会为您处理转义,并确保文档格式正确。

This pageshows the basics of using the HtmlTextWriterclass, the gist of which being:

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

StringWriter stringWriter = new StringWriter();

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

回答by SpliFF

When I deal with this problem in other languages I go for a separation of code and HTML. Something like:

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

1.) Create a HTML template. use [varname]placeholders to mark replaced/inserted content.
2.) Fill your template variables from an array or structure/mapping/dictionary

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

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

回答by Jimmy

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

回答by Jacob

You can use ASP.NET to generate your HTML outside the context of web pages. Here's an articlethat shows how it can be done.

您可以使用 ASP.NET 在网页上下文之外生成 HTML。 这是一篇文章,展示了如何做到这一点。

回答by JaredPar

The most straight forward way is to use an XmlWriter object. This can be used to produce valid HTML and will take care of all of the nasty escape sequences for you.

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

回答by Matias

You could write your own classes with its Render method, and another attributes, to avoid a great mess if you use it a lot, and then use the HTMLWriter or the xmlwriter as well. This logic is used in the asp.net pages, you can inherit from webControl and override the render method, wich is great if you are developing server-side controls.
Thiscould be a good example.

您可以使用其 Render 方法和其他属性编写您自己的类,以避免在您经常使用它时造成混乱,然后也使用 HTMLWriter 或 xmlwriter。这个逻辑在asp.net页面中使用,你可以继承webControl并覆盖render方法,如果你正在开发服务器端控件,这非常棒。
可能是一个很好的例子。

Regards

问候

回答by Jeff Wilcox

It really depends what you are going for, and specifically, what kind of performance you really need to offer.

这实际上取决于您的目标,特别是您真正需要提供什么样的性能。

I've seen admirable solutions for strongly-typed HTML development (complete control models, be it ASP.NET Web Controls, or similar to it) that just add amazing complexity to a project. In other situations, it is perfect.

我见过令人钦佩的强类型 HTML 开发解决方案(完整的控件模型,无论是 ASP.NET Web 控件,还是类似的),这些解决方案只是为项目增加了惊人的复杂性。在其他情况下,它是完美的。

In order of preference in the C# world,

按照 C# 世界中的优先顺序,

  • ASP.NET Web Controls
  • ASP.NET primitives and HTML controls
  • XmlWriter and/or HtmlWriter
  • If doing Silverlight development with HTML interoperability, consider something strongly typed like link text
  • StringBuilder and other super primitives
  • ASP.NET Web 控件
  • ASP.NET 原语和 HTML 控件
  • XmlWriter 和/或 HtmlWriter
  • 如果使用 HTML 互操作性进行 Silverlight 开发,请考虑强类型的内容,例如链接文本
  • StringBuilder 和其他超级原语

回答by Josh

You could use System.Xml.Linqobjects. They were totally redesigned from the old System.Xmldays which made constructing XML from scratch really annoying.

你可以使用System.Xml.Linq对象。它们是从过去完全重新设计的,System.Xml这使得从头开始构建 XML 真的很烦人。

Other than the doctype I guess, you could easily do something like:

除了我猜的 doctype 之外,您可以轻松地执行以下操作:

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

回答by Jim Wallace

I know you asked about C#, but if you're willing to use any .Net language then I highly recommend Visual Basic for this exact problem. Visual Basic has a feature called XML Literals that will allow you to write code like this.

我知道你问过 C#,但如果你愿意使用任何 .Net 语言,那么我强烈推荐 Visual Basic 来解决这个确切的问题。Visual Basic 有一项称为 XML 文字的功能,它允许您编写这样的代码。

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

This allows you to write straight HTML with expression holes in the old ASP style and makes your code super readable. Unfortunately this feature is not in C#, but you could write a single module in VB and add it as a reference to your C# project.

这允许您以旧的 ASP 样式编写带有表达式漏洞的直接 HTML,并使您的代码具有超级可读性。不幸的是,C# 中没有此功能,但您可以在 VB 中编写单个模块并将其添加为对 C# 项目的引用。

Writing in Visual Studio also allows proper indentation for most XML Literals and expression wholes. Indentation for the expression holes is better in VS2010.

在 Visual Studio 中编写还允许对大多数 XML 文字和表达式整体进行适当的缩进。VS2010 中表达孔的缩进更好。

回答by Dan Herbert

If you're looking to create an HTML document similar to how you would create an XML document in C#, you could try Microsoft's open source library, the Html Agility Pack.

如果您希望创建类似于在 C# 中创建 XML 文档的方式的 HTML 文档,您可以尝试 Microsoft 的开源库Html Agility Pack

It provides an HtmlDocument object that has a very similar API to the System.Xml.XmlDocumentclass.

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