how to replace <br> tag with <br/> tag using HtmlAgilityPack?

c# html-agility-pack

Question

Quite strange! When I load & replace with an empty string using

 var document = new HtmlDocument();
    document.LoadHtml(data); 
    document.DocumentNode.OuterHtml.Replace("<tbody>", "");

This works fine & <tbody> will be removed.

Same way when I try to replace <br> with <br/> using,

document.DocumentNode.OuterHtml.Replace("<br>", "<br/>");

It does not work :(

also tried,

 var brTags = document.DocumentNode.SelectNodes("//br");
            if (brTags != null)
            {
                foreach (HtmlNode brTag in brTags)
                {
                    brTag.OuterHtml = "<br/>";
                    // brTag.Name= "br/"; - > Also this one :(
                }
            }

HTMLAgilityPack's replace() function does not work for self closing tags?

Accepted Answer

document.OptionWriteEmptyNodes = true;

Will do the trick for you!


Popular Answer

You don't have to replace <br> by <br/> manually, if you need to close the node, just instruct the library to do so, for example this:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("<br/>");
doc.Save(Console.Out);

will output this:

<br>

and this

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("<br/>");
doc.OptionWriteEmptyNodes = true;
doc.Save(Console.Out);

will output this:

<br />



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