Add a doctype to HTML via HTML Agility pack

家住魔仙堡 提交于 2019-12-01 04:13:53

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.

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>";
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!