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
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>";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With