在C#中编写html

45 html c#

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

-edit-我当时不知道但我可以写

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"); 
Run Code Online (Sandbox Code Playgroud)

它会工作,但需要更换所有"与"

lc.*_*lc. 88

你可能最好使用一个HtmlTextWriterXMLWriter一个普通的平原StringWriter.他们将为您提供帮助,并确保文档格式正确.

此页面显示了使用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();
Run Code Online (Sandbox Code Playgroud)

  • +1为好答案+链接到示例页面 (2认同)

Spl*_*iFF 24

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

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

Write( FillTemplate(myHTMLTemplate, myVariables) ) # pseudo-code
Run Code Online (Sandbox Code Playgroud)


Jim*_*ace 14

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

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
Run Code Online (Sandbox Code Playgroud)

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

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


Dan*_*olf 12

使用an XDocument创建DOM,然后使用a写出来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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会生成以下输出:

<!DOCTYPE html >
<html>
    <head />
    <body>
        <p>This paragraph contains <b>bold</b> text.</p>
        <p>This paragraph has just plain text.</p>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)


Jim*_*mmy 6

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);
Run Code Online (Sandbox Code Playgroud)

  • 根据标题的来源,您可能希望在盲目地将其插入字符串之前对标题进行HTML编码. (2认同)

Jos*_*osh 6

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

除了我猜的文档类型,您可以轻松地执行以下操作:

var html = new XElement("html",
    new XElement("head",
        new XElement("title", "My Page")
    ),
    new XElement("body",
        "this is some text"
    )
);
Run Code Online (Sandbox Code Playgroud)


Jar*_*Par 5

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


ole*_* wx 5

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

  • 这是一种非常酷的方法。如果您提供了更多详细信息,您可能会获得更多的选票。 (2认同)