【问题标题】:Generating HTML page in C# application在 C# 应用程序中生成 HTML 页面
【发布时间】:2011-12-01 23:41:52
【问题描述】:

我正在编写一个需要生成 HTML 页面的 C# 应用程序。只有部分 HTML(如标题)需要由 C# 应用程序定义。基本标记等是静态的。

以标题为例,目前我正在这样做。 我将基本的 html 保存为 txt 文件。这是一部分:

    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
        <title>Title goes here</title>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>

我在我的 C# 应用程序中将其读入字符串(线框),然后为了更改标题,我做了一个

oldtitle = "<title>Title goes here</title>";
newtitle = "<title>This is the title I want</title>";
wireframe = wireframe.Replace(oldtite,newtitle);

以上只是一个例子。字符串线框实际上由整个 html 代码组成。我想知道我这样做的方式是否有效?我猜不是因为要更改标题,而是在搜索整个字符串。

实现这一目标的更有效方法是什么?

【问题讨论】:

    标签: c# html string


    【解决方案1】:

    我有类似的任务。我有一个恒定的 html 结构,我需要粘贴数据。 我定义了 XSLT,并在接收数据时进行了 XSLT 转换。 它工作得很快。

    【讨论】:

    • 嗯,很有趣。粗略地看一下 XSLT 似乎就是我所需要的。我会进一步研究它并尝试实施它。谢谢!
    【解决方案2】:

    您可以使用 IndexOf 方法只查找一次,例如:

    int index = wireframe.IndexOf(oldtitle);
    wireframe = wireframe.Substring(0, index) + newtitle + wireframe.Substring(index + oldtitle.length);
    

    【讨论】:

      【解决方案3】:

      我相信您可以使用 String.Format 完成您想要做的事情

      http://msdn.microsoft.com/en-us/library/system.string.format.aspx

      模板文件可能如下所示:

      <head>
          <meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
          <title>{0}</title>
          <link rel="stylesheet" type="text/css" href="style.css" />
      </head>
      

      然后

      string input = ... // <-- read the "template" file into this string
      string output = String.Format(input, newTitle);
      

      我相信这样会更有效率。

      【讨论】:

      • 我看到的问题是它不是很灵活。标记中间的微小变化将意味着更改所有随后的索引。
      猜你喜欢
      • 2011-02-03
      • 2019-01-12
      • 2012-06-28
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多