C# – HTML Agility Pack stripping self-closing tags from input

asp.netchtml-agility-packnet

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))
        {
            control.RenderControl(htmlWriter);
        }
    }
    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;
}
inputNode.ParentNode.RemoveChild(inputNode);

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?

Best Answer

Try setting "OptionWriteEmptyNodes" flag:

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

// ....

UPDATE

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

Related Topic