[英]How to parse doctype to string as html doctype
我正在使用 C# 應用程序從EnumWindows 的當前 IE 選項卡中獲取 html 文件。 現在我得到了 HTMLDocument 並且可以通過HtmlAgilityPack 將其從 outerHTML ( {HTMLDocument}.documentElement.outerHTML ) 解析為 html 文件,但我的輸出 html 文件沒有 doctype。
我看到HTMLDocument具有doctype屬性,如何將其解析為與 html 文件中的標簽相同的字符串
我通過將htmlDocument.doctype
為動態對象來獲得它。 另外,您可以通過循環(dynamic)htmlDocument.childNodes
列表來獲取<html>
標簽之外的其他標簽
private static void InsertDocType(HTMLDocument htmlDocument, HtmlDocument document)
{
// get html node
HtmlNode htmlNode = document.DocumentNode.SelectSingleNode("/html");
// get doctype node from HTMLDocument
var doctype = (dynamic)htmlDocument.doctype;
StringBuilder doctypeText = new StringBuilder();
doctypeText.Append("<!DOCTYPE");
doctypeText.Append(" ");
doctypeText.Append(doctype.name);
// add PUBLIC
if (!string.IsNullOrEmpty(doctype.publicId))
{
doctypeText.Append(" PUBLIC \"");
doctypeText.Append(doctype.publicId);
doctypeText.Append("\"");
}
// add sytem id
if (!string.IsNullOrEmpty(doctype.systemId))
{
doctypeText.Append(" \"");
doctypeText.Append(doctype.systemId);
doctypeText.Append("\"");
}
// add close tag
doctypeText.Append(">");
doctypeText.Append(Environment.NewLine);
HtmlCommentNode doctypeNode = document.CreateComment(doctypeText.ToString());
document.DocumentNode.InsertBefore(doctypeNode, htmlNode);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.