gpt4 book ai didi

c# - 将 HTML 写入字符串

转载 作者:IT王子 更新时间:2023-10-29 03:53:25 24 4
gpt4 key购买 nike

我有这样的代码。有没有办法让它更容易编写和维护?使用 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。他们会为您转义,并确保文档格式正确。

This page显示了使用 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();

关于c# - 将 HTML 写入字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1004776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com