我正在开发 C# 应用程序以通过EnumWindows从当前 IE 选项卡获取 html 文件。现在我得到了 HTMLDocument 并可以通过HtmlAgilityPack将其从 outerHTML ( {HTMLDocument}.documentElement.outerHTML )解析为 html 文件,但我的输出 html 文件没有 doctype。
我看到HTMLDocument具有doctype属性,如何将其解析为与 html 文件中的标记相同的字符串
我正在开发 C# 应用程序以通过EnumWindows从当前 IE 选项卡获取 html 文件。现在我得到了 HTMLDocument 并可以通过HtmlAgilityPack将其从 outerHTML ( {HTMLDocument}.documentElement.outerHTML )解析为 html 文件,但我的输出 html 文件没有 doctype。
我看到HTMLDocument具有doctype属性,如何将其解析为与 html 文件中的标记相同的字符串
我通过转换htmlDocument.doctype
为动态对象来获得它。另外,您可以通过在列表<html>
上循环来获取其他标签之外的标签(dynamic)htmlDocument.childNodes
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);
}