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
turns to&nbsp;
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 i开发者_运维问答t when creating a new element/node.
I found the answer: the P tag has to be created off the HtmlDocument
instance using the CreateElement(..)
factory method like so:
var hdoc = new HtmlDocument(); // HTML doc instance
// ... stuff
HtmlNode p = hdoc.CreateElement("p"); // << will close itself for XHTML.
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.
HtmlNode.ElementsFlags["p"] = HtmlElementFlag.Closed;
Default value for "p" is "Empty | Closed". You should to set it as "Closed" to return:
<p></p>
精彩评论