HTML Agility Pack stripping self-closing tags from input

.net c# html-agility-pack


This is how I'm creating my checkbox:

HtmlInputCheckBox checkbox = new HtmlInputCheckBox();
checkbox.ID = _Data.ControlID;
checkbox.Attributes.Add("class", "checkbox");
checkbox.Attributes.Add("autocomplete", "off");
sReplacementString = element.RenderToString();

RenderToString is an extension that does this:

public static string RenderToString(this Control control)
    StringBuilder sb = new StringBuilder();
    using (StringWriter writer = new StringWriter(sb))
        using (HtmlTextWriter htmlWriter = new HtmlTextWriter(writer))
    return sb.ToString();

This produces a string with a closing tag on the input, I can see this when debugging.

<input name="ttWBF_1" type="checkbox" id="ttWBF_1" autocomplete="off" class="checkbox" />

It's then added to the HTML using the Agility Pack as such:

HtmlNode temp = doc.CreateElement("temp");
temp.InnerHtml = sReplacementString;
HtmlNode current = inputNode;

foreach (HtmlNode child in temp.ChildNodes)
    inputNode.ParentNode.InsertAfter(child, current);
    current = child;

However in the HTML the input tag for the checkbox is missing its self-closing slash and therefore fails WC3 validation.

<input name="ttWBF_1" type="checkbox" id="ttWBF_1" autocomplete="off" class="checkbox">

This happens with my textboxes which are generated in the same way. it looks like they're getting lost when adding the HTML to the page using the agility pack.

How do I prevent this?

Accepted Answer

In the end it pains me to say that I fell back on processing the HTML with regex to add in the mising self-closing tag. I'd love a better solution as this is hacky and not future proof - it has to be added in for every tag that needs correcting:

sXHTML = Regex.Replace(sXHTML, "<input(.*?)>", "<input $1 />");

Popular Answer

Try setting "OptionWriteEmptyNodes" flag:

HtmlDocument doc = new HtmlDocument();
doc.OptionWriteEmptyNodes = true;

// ....


Since my original answer was rejected, here's another possible solution.

Are you passing the correct DOCTYPE to your HTML document before rendering it? Take a look at this SO question for how to insert a DOCTYPE: Add a doctype to HTML via HTML Agility pack

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why