Use System.Xml.XmlDocument to create HTML in C#

If you need to create HTML, it is usually a bad idea to just concatenate strings together. It tends to create brittle and invalid documents once there is any level of complexity to it. You need to manage the position of each tag and when to close it, where to insert data, and changing the formatting is a chore. Since HTML is a tree-like data structure, it is much better to model it as such inside your program.

The best option is usually to a bonifide HTML parser/generator. Most languages either include it in the standard library or has a defacto external library that most users work with. When I was working with C#, I found that I needed to generate a simple HTML document but found that there was nothing in standard library explicitly for it. However, C# does have excellent standard library support for XML.

While HTML is not XML, their formats are similar enough that if you know the differences, XML generators can create valid HTML documents easily. For my purposes, installing an external HTML generator would have been an irrelevant dependency on my project, so the built in System.Xml.XmlDocument seemed a better fit.

Below is a code snippet that will create a basic, valid HTML document as a string. I didn't want to include anything XML specific like namespaces or CDATA tags, so I specifically omitted solutions that required additional configuration to get rid of these. Note that you need to use doc.outerXml to get the string data from the object. The native doc.toString() will not convert the document to a string.

using System.Xml;  
public string GenerateHtml()  
{
    var doc = new XmlDocument();
    var htmlRoot = doc.CreateElement("html");
    doc.AppendChild(htmlRoot);
    var body = doc.CreateElement("body");
    body.AppendChild(doc.CreateTextNode("Hello world"));
    htmlRoot.AppendChild(body);
    return doc.OuterXml;
}

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA