2011-10-06 66 views
1

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

给出标题的例子,目前我正在这样做。 我把基本的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代码组成。我想知道我做的这种方式是否有效?我猜想,既然改变了标题,我正在搜索整个字符串。

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

回答

4

我有一个类似的任务。我有一个恒定的HTML结构,我需要粘贴数据。 我定义了XSLT,当接收到数据时,我做了XSLT转换。 它工作得很快。

+1

+1 XSLT是解决此问题的绝佳解决方案。 – mikey

+0

嗯,有趣。粗略浏览一下XSLT就好像是我需要的。我会进一步研究并尝试实施它。谢谢! – xbonez

0

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

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

我相信你可以做到你想用的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); 

我相信这会更有效率。

+0

我看到的问题是,它不是很灵活。标记中间的轻微变化意味着要改变随后的所有指标。 – xbonez