I have an html with <div><h1> hello Hi</div> <div>hi </p></div>
Required Output : <div><h1> hello </h1></div> <div><p>hi </p></div>
Using HTML agility pack is it possible to fix this kind of similar issues with missing closing and opening tags?
An opening tag begins a section of page content, and a closing tag ends it. For example, to markup a section of text as a paragraph, you would open the paragraph with an opening paragraph tag <p> and close it with a closing paragraph tag </p> (closing tags always proceed the element with a /).
You can use the Auto-Format feature (Ctrl+K+D) of Microsoft Visual Studio - it reformats your code so that you can easily see whether there are missing tags. I love this feature, it often comes in handy. Save this answer.
It is used to indicate that there is no content between the opening and closing tags. Some few examples of self-closing tags in HTML are <input/>, <hr/>, <br/>, <img/>, etc. Self-closing tags in HTML only have attributes and do not contain any content, and they also cannot have any children.
The void elements or singleton tags in HTML don't require a closing tag to be valid. These elements are usually ones that either stand alone on the page or where the end of their contents is obvious from the context of the page itself.
The library isn't intelligent enough to create the opening p
where you put it, but it's intelligent enough to create the missing h1
. And in general, it creates valid HTML always, but not always the one you would expect.
So this code:
HtmlDocument doc = new HtmlDocument();
doc.Load(yourhtml);
doc.Save(Console.Out);
will dump this:
<div><h1> hello Hi</h1></div> <div>hi <p></div>
Which is not what you want, but is valid HTML. You can also add a little trick like this:
HtmlNode.ElementsFlags["p"] = HtmlElementFlag.Closed;
HtmlDocument doc = new HtmlDocument();
doc.Load(yourhtml);
doc.Save(Console.Out);
that will dump this:
<div><h1> hello Hi</h1></div> <div>hi <p></p></div>
When doing
HtmlAgilityPack.HtmlDocument.LoadHTML(yourhtml)
HTMLAgilityPack will automatically fix the tags for you, and then you can access those tags using: HtmlAgilityPack.HtmlDocument.DocumentNode.OuterHTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With