'How to create an empty XHTML compliant P node using HTML Agility Pack 1.4.0?

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 &nbsp; turns to &amp;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 values Closed, Empty, CData, CanOverlap (Closed might be useful) but cannot see where I would apply it when creating a new element/node.


Solution 1:[1]

HtmlNode.ElementsFlags["p"] = HtmlElementFlag.Closed;

Default value for "p" is "Empty | Closed". You should to set it as "Closed" to return:

<p></p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 EminST