Add doctype to HTML via HTML Agility pack

I know that it's easy to add elements and attributes to HTML documents using the HTML agility package. But how can I add doctype (e.g. HTML5) in an HtmlDocument with html service pack? Thanks you

+6
source share
2 answers

The Html Agility score parser treats doctype as a node comment. To add a doctype to an HTML document, just add a node comment with the desired doctype at 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 validate the existing doctype type.

+6
source

As far as I know, AgilityPack does not have a direct method for installing doctype, but as Hans mentioned, HAP treats doctype as a node comment. Thus, you can first try to find an existing doctype, if not create a new one, and insert the 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>"; 
+8
source

Source: https://habr.com/ru/post/912126/


All Articles