Add a doctype to HTML via HTML Agility pack

寵の児 提交于 2019-12-01 01:14:14

问题


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


回答1:


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.




回答2:


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>";


来源:https://stackoverflow.com/questions/9957525/add-a-doctype-to-html-via-html-agility-pack

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