Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix html tags(which is missing the <open> & <close> tags) with HTMLAgilityPack

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?

like image 218
ragmn Avatar asked Aug 23 '13 06:08

ragmn


People also ask

How do you create an open tag in HTML?

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 /).

How do I find missing tags in HTML?

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.

Why are some tags self closing?

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.

Why some HTML tags are not closed?

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.


2 Answers

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>
like image 166
Simon Mourier Avatar answered Nov 15 '22 20:11

Simon Mourier


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

like image 25
user2280232 Avatar answered Nov 15 '22 19:11

user2280232