TheAuzzieJesus TheAuzzieJesus - 4 months ago 45
HTML Question

Writing a <meta> tag using HTMLTextWriter in C# issue

I'm trying to render a basic HTML webpage using

C#
and
HTMLTextWriter
to output to a
WebBrower
object, but am having issues rendering the
<meta>
tag in my
HTML
output.

What I am expecting to be output..

<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>My Website</title>
</head>

<body>
<h1>Hello World!</h1>
</body>

</html>


What is currently being output..

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</meta charset="UTF-8"><title>
My Website
</title>
</head><body>
<h1>
Hello World!
</h1>
</body>
</html>



Notice how the
<meta>
tag is being output as
<meta charset="UTF-8">
&
</meta charset="UTF-8">
instead of just
<meta charset="UTF-8">
.

What can I do to correct this issue?


Here is the code I am using..

var sw = new StringWriter();
using (var writer = new HtmlTextWriter(sw)) {
writer.RenderBeginTag("!DOCTYPE html");
writer.RenderBeginTag(HtmlTextWriterTag.Html);
writer.RenderBeginTag(HtmlTextWriterTag.Head);
writer.RenderBeginTag("meta charset=\"UTF-8\"");
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Title);
writer.Write("SIT323 - My Website");
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderBeginTag(HtmlTextWriterTag.Body);
writer.RenderBeginTag(HtmlTextWriterTag.H1);
writer.Write("Hello World!");
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderEndTag();
};
return sw.ToString();

RAM RAM
Answer

Try it:

writer.AddAttribute("charset", "UTF-8");
writer.RenderBeginTag(HtmlTextWriterTag.Meta);
writer.RenderEndTag();

Result:

<meta charset="UTF-8">

The coding pattern for rendering markup elements is as follows:

1- Use the AddAttribute method to add any attributes to the element.

2- Use the RenderBeginTag method.

3- Use other methods as needed to render the content found between the element's opening and closing tags.

4- Use the RenderEndTag method.