Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 593
user2729272 Avatar asked Sep 02 '13 09:09

user2729272


3 Answers

document.OptionWriteEmptyNodes = true;

Will do the trick for you!

like image 191
ragmn Avatar answered Nov 07 '22 10:11

ragmn


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 />
like image 7
Simon Mourier Avatar answered Nov 07 '22 11:11

Simon Mourier


StringWriter writer = new StringWriter();
var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings() { OmitXmlDeclaration = true });
document.OptionOutputAsXml = true;

document.Save(xmlWriter);
var newHtml = writer.ToString();
like image 2
EZI Avatar answered Nov 07 '22 10:11

EZI