Add a doctype to HTML via HTML Agility pack

.net c# html-agility-pack

Question

I know it is easy to add elements and attributes to HTML documents with the HTML agility pack. But how can I add a doctype (e.g. the HTML5 one) to an HtmlDocument with the html agility pack? Thank you

Accepted Answer

The Html Agility Pack parser treats the doctype as a comment node. In order to add a doctype to an HTML document simply add a comment node with the desired doctype to the beginning of the document:

HtmlDocument htmlDoc = new HtmlDocument();

htmlDoc.Load("withoutdoctype.html");

HtmlCommentNode hcn = htmlDoc.CreateComment("<!DOCTYPE html>");

HtmlNode htmlNode = htmlDoc.DocumentNode.SelectSingleNode("/html");
htmlDoc.DocumentNode.InsertBefore(hcn, htmlNode);

htmlDoc.Save("withdoctype.html");

Please note, that my code does not check for the existing of a doctype.


Popular Answer

As far as I know AgilityPack doesn't have a direct method to set the doctype, but as Hans mentioned, HAP treats the doctype as a comment node. So you could try to find the existing doctype first, if not create a new one and paste a desired value there:

var doctype = doc.DocumentNode.SelectSingleNode("/comment()[starts-with(.,'<!DOCTYPE')]");
if (doctype == null)
    doctype = doc.DocumentNode.PrependChild(doc.CreateComment());

doctype.InnerHtml = "<!DOCTYPE html>";



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why