如何使用 HTML Agility Pack 1.4.0 创建空的 XHTML 兼容 P 节点?
然而,我尝试为 P 标签创建一个 HTMLNode 并将其注入到 HTMLDocument DOM 中,它始终显示为未闭合的标签。例如。
// different ways I've tried creating the node:
var p = HtmlNode.CreateNode("<p />");
var p = HtmlNode.CreateNode("<p></p>");
var p = HtmlNode.CreateNode("<p>");
var p = HtmlTextNode.CreateNode("<p></p>");
// some other properties I've played with:
p.Name = "p";
p.InnerHtml = "";
使用 .Save()
方法后,它们最终都在输出中以
形式出现。
我希望它对于 XHTML 正确关闭,例如
或
我的解决方法:我可以做的是发出 CreateNode("")
(中间有一个空格),它保留整个源代码,但我认为必须有更好的方法。
尝试或考虑的其他选项:
当我打开选项
.OutputAsXml
时,它会转义现有实体,例如
变为& amp;nbsp;
这并不理想,并且它不会关闭我注入的 P 标记。当我启用选项
.OptionWriteEmptyNodes
时,它仍然不会关闭我注入的P标签。- 我看到 Agility Pack 包含枚举
HtmlElementFlag
,其值为Closed、Empty、CData、CanOverlap
(Closed 可能有用),但无法看到在创建新项目时将在何处应用它元素/节点。
However I try to create an HTMLNode for the P tag and inject it into the HTMLDocument DOM, it always appears as an unclosed tag. For example.
// different ways I've tried creating the node:
var p = HtmlNode.CreateNode("<p />");
var p = HtmlNode.CreateNode("<p></p>");
var p = HtmlNode.CreateNode("<p>");
var p = HtmlTextNode.CreateNode("<p></p>");
// some other properties I've played with:
p.Name = "p";
p.InnerHtml = "";
They all end up as just <p>
in the output after using the .Save()
method.
I want it properly closed for XHTML like <p />
or <p></p>
. Either is fine.
My workaround: What I can do is issue CreateNode("<p> </p>")
(with a space in between) and it retains the entire source, but I think there has to be a better way.
Other options tried or considered:
When I turn on the option
.OutputAsXml
it escapes the existing entities, for example
which is not ideal, and it doesn't close my injected P tag.when I enable the option
.OptionWriteEmptyNodes
it still doesn't close my injected P tag.- I see the Agility Pack contains the enum
HtmlElementFlag
with valuesClosed, Empty, CData, CanOverlap
(Closed might be useful) but cannot see where I would apply it when creating a new element/node.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我找到了答案:必须使用
CreateElement(..)
工厂方法从HtmlDocument
实例创建 P 标记,如下所示:然后 P 将像
一样关闭自身>
。
如果您像我在问题中尝试的那样使用 HtmlNode.CreateNode(..) 工厂方法创建 HtmlNode 实例,则就关闭而言,它在 DOM 中的行为有所不同。
I found the answer: the P tag has to be created off the
HtmlDocument
instance using theCreateElement(..)
factory method like so:Then P will close itself like
<p />
.If you instead create an HtmlNode instance using the HtmlNode.CreateNode(..) factory method like I was trying in the question, it behaves differently in the DOM as far as closure.
“p”的默认值为“空 | 关闭”。您应该将其设置为“已关闭”才能返回:
Default value for "p" is "Empty | Closed". You should to set it as "Closed" to return: