ala*_*eno 7 .net c# html-agility-pack
我知道使用HTML敏捷包向HTML文档添加元素和属性很容易.但是如何使用html敏捷包将文档类型(例如HTML5)添加到HtmlDocument?谢谢
Ale*_*lex 11
据我所知,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>";
Run Code Online (Sandbox Code Playgroud)
Html Agility Pack解析器将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");
Run Code Online (Sandbox Code Playgroud)
请注意,我的代码不会检查doctype的现有情况.
| 归档时间: |
|
| 查看次数: |
3045 次 |
| 最近记录: |