HtmlAgilityPack:有人可以准确解释将 HtmlDocument OptionAutoCloseOnEnd 设置为 true 的效果吗?

HtmlAgilityPack: Could someone please explain exactly what is the effect of setting the HtmlDocument OptionAutoCloseOnEnd to true?

当前文档说:

Defines if closing for non closed nodes must be done at the end or directly in the document. Setting this to true can actually change how browsers render the page. Default is false.

对不起,我不得不承认我不明白这段话。具体"at the end"的是什么? "in the document" 到底是什么意思?最后一个之前的短语听起来不祥。如果该选项设置为 true 并且 html 格式正确,这是否仍会影响文档?

我查看了源代码,但我不明白发生了什么 - 代码对 属性 未设置为 true 做出反应。请参阅第 1113 和 1154 行的 HtmlNode.cs, and search for OptionAutoCloseOnEnd - line 1707. I also found some funky code in HtmlWeb.cs。可惜源代码浏览器不显示行号,而是在页面中搜索 OptionAutoCloseOnEnd。

能否举例说明此选项的作用?

我正在使用 HtmlAgilityPack 修复一些错误 html 并将页面内容导出到 xml。

我遇到了一些格式错误的 html - 重叠标签。这是片段:

<p>Blah bah
<P><STRONG>Some Text</STRONG><STRONG></p>
<UL>
<LI></STRONG>Item 1.</LI>
<LI>Item 2</LI>
<LI>Item 3</LI></UL>

注意第一个 p 标签没有关闭,注意重叠的 STRONG 标签。

如果我设置 OptionAutoCloseOnEnd,这会以某种方式得到修复。我试图了解在文档结构中通常将此 属性 设置为 true 到底有什么影响。

这是我正在使用的 C# 代码:

HtmlDocument doc = new HtmlDocument();
doc.OptionOutputAsXml = true;
doc.OptionFixNestedTags = true;      
//  doc.OptionAutoCloseOnEnd = true;    
doc.LoadHtml(htmlText);

谢谢!

使用 HtmlAgilityPack 的更好方法是在需要时以编程方式打开和关闭标签并设置:

 doc.OptionAutoCloseOnEnd = false;

这将为您提供预期的格式。

否则,该库将检查是否有任何未关闭的标签,并根据您的代码执行流程在合适的地方关闭它们。

当前代码总是在父节点关闭之前关闭未关闭的节点。所以下面的代码

var doc = new HtmlDocument();
doc.LoadHtml("<x>hello<y>world</x>");
doc.Save(Console.Out);

会输出这个(未关闭的<y>在父<x>关闭之前关闭)

<x>hello<y>world</y></x>

最初,设置该选项是为了能够生成此选项(不适用于 XML 输出类型):

<x>hello<y>world</x></y>

结束 <y> 设置在文档末尾(这就是 "end" 的意思)。请注意,在这种情况下,您仍然可以获得重叠元素。

这个功能(我承认可能没用)在过去的某个地方被破坏了,我不知道为什么。

注意 <p> 标记大小写是特殊的,因为它默认由自定义 HtmlElementFlag 管理。这是它在 HtmlNode.cs:

中的声明方式
ElementsFlags.Add("p", HtmlElementFlag.Empty | HtmlElementFlag.Closed);