通过HTML敏捷包向HTML添加doctype

本文关键字:HTML 添加 doctype 通过 | 更新日期: 2023-09-27 18:29:40

我知道用HTML敏捷包向HTML文档添加元素和属性很容易。但是,如何使用html敏捷性包将doctype(例如HTML5)添加到HtmlDocument?感谢

通过HTML敏捷包向HTML添加doctype

据我所知,AgilityPack没有直接方法来设置doctype,但正如Hans所提到的,HAP将doctype视为注释节点。因此,您可以尝试先找到现有的doctype,如果不创建新的doctype并在那里粘贴所需的值:

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

Html敏捷包解析器将doctype视为注释节点。为了将doctype添加到HTML文档中,只需添加在文档开头添加所需doctype的注释节点:

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

请注意,我的代码不检查doctype的存在。