c# - HtmlAgilityPack 在 OuterHtml 中生成缺失的结束标签

标签 c# html html-agility-pack

我正在使用 HtmlAgilityPack 来解析和操作 html 文本。然而,DocumentNode.OuterHtml 似乎缺少结束标记。

为了隔离问题,现在我什么都不做,只是解析并获取 OuterHtml(无操作):

var document = new HtmlDocument();
document.LoadHtml(myHtml);
result = document.DocumentNode.OuterHtml;

原文:(myHtml)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="X-UA-Compatible" content="IE=Edge" /><title>
     MyTitle
</title>

OutputHtml:(结果)注意元元素未关闭

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="X-UA-Compatible" content="IE=Edge"><title>
    MyTitle
</title>

类似地,所有 input 和 img 元素都保持打开状态。 (请不要回答这不应该是一个问题。好吧,它不应该是,但确实是。)Chrome 无法正确渲染页面。继续阅读。

更奇怪的是:

原文:(myHtml)

    <option value="10">Afrikaans</option>
    <option value="11">Albanian</option>
    <option value="12">Arabic</option>
    <option value="13">Armenian</option>
    <option value="14">Azerbaijani</option>
    <option value="15">Basque</option>

OutputHtml:(结果)请注意,缺少完整的显式结束标记

    <option value="10">Afrikaans
    <option value="11">Albanian
    <option value="12">Arabic
    <option value="13">Armenian

使用 HtmlAgilitPack 最新 NuGet 包:id="HtmlAgilityPack"version="1.4.9"

最佳答案

加载文档时可以设置多个选项。

<强> OptionAutoCloseOnEnd

定义是否必须在文档末尾或直接在文档中关闭非关闭节点。将其设置为 true 实际上可以改变浏览器呈现页面的方式。

document = new HtmlDocument();
document.OptionAutoCloseOnEnd = true;
document.LoadHtml(content);

值得一读的相关资源:

HtmlAgilityPack Drops Option End Tags

Image tag not closing with HTMLAgilityPack

关于c# - HtmlAgilityPack 在 OuterHtml 中生成缺失的结束标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179687/

相关文章:

c# - 使用正确的换行符将 HTML 转换(呈现)为文本

javascript - 使用 HTML 从 SELECT 中删除自动完成功能

PHP - 解析 HTML 字符串中的纯文本

c# - 如何选择包含特定关键字的表 - c# - xpath - htmlagilitypack

c# - 如何使用 SqlDataReader 读取行数

c# - 在打开表单之前设置所有标签字体

c# - 为什么这个 ListView CheckBox 绑定(bind)到整个 View 模型而不是行项目?

jquery - 居中全屏响应图像 - Jquery 方法

c# - YouTube HTML Agility Pack C#

c# - 使用 html 敏捷包解析表单操作并输入名称和值