开发者

Generating HTML page in C# application

开发者 https://www.devze.com 2023-04-11 16:09 出处:网络
I\'m writing a C# application that needs to generate an HTML page. Only parts of the HTML (such as the title) need to be defined by the C# app. Basic markup etc is static.

I'm writing a C# application that needs to generate an HTML page. Only parts of the HTML (such as the title) need to be defined by the C# app. Basic markup etc is static.

Giving the example of title, currently I'm doing it this way. I have the basic html saved as a txt file. here's a portion:

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

I read this into a string (wireframe) in my C# app, and then to change the title, I do a

oldtitle = "<title>Title goes here</title>";
newtitle = "<title>This i开发者_运维知识库s the title I want</title>";
wireframe = wireframe.Replace(oldtite,newtitle);

The above is just an example. the string wireframe actually consists of the entire html code. I'm wondering if the way I'm doing it is efficient? I'm guessing not since to change the title, I'm searching through the entire string.

What would be a more efficient way to achieve this?


I had a similar task. I had a constant html structure and I needed to paste data. I defined XSLT and when receivng a data I did XSLT transformation. It worked fast.


You could use IndexOf Method to look up only once, for example:

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


I believe you can accomplish what you're trying to do with String.Format

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

Template file could look like:

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

Then

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

I believe this would be more efficient.

0

精彩评论

暂无评论...
验证码 换一张
取 消