HTML Agility Pack Fix <li> list order

.net c# html html-agility-pack

Question

I have been trying to use the HTML Agility Pack to parse HTML into valid XHTML to go into a larger XML file. This for the most part works however lists become formatted like:

<ul>
    <li>item1
    <li>item2
    </li></li>
</ul>

As oppose to what I would expect:

<ul>
    <li>item1</li>
    <li>item2</li>
</ul>

Unfortunately this format with nested li tags doesn't pass the schema validation which I have no control over. Does anyone know a simple way to correct this either through the HTML Agility Pack or an alternative. Preferably in .NET.

Accepted Answer

I found an alternative to the agility pack called HTML Tidy http://tidy.sourceforge.net/ I actually used the .NET port called Tidy.NET http://sourceforge.net/projects/tidynet/ this seemed to fix my issue.


Popular Answer

I found your questio on other sites as well. The HTML you are trying to parse is:

<UL>
<LI>NVQ Level 3 in Fabrication and Welding Engineering
<LI>Level 3 Certificate in Engineering
<LI>Level&nbsp;2 Key Skill in Application of Number
<LI>Level&nbsp;2 Key Skill in Communication
<LI>Level&nbsp;2 Key Skill in Information Technology
<LI>Level 2 Key Skill in Working with Others
<LI>Level 2 Key Skill in Improving Own Learning &amp; Performance</LI></UL>

What I notice is that the first <li> is parent to the other <li>'s. One aproach I would take at this is to take the first <li> and the text (it's a TextNode for HAP), save the other <li> children and remove the children, inserting them (while formating them) after the parent node.
You might have to take the recursive way at this. Here is a peek at my solutuion for a HTML Sanitizer class: HTML Agility Pack strip tags NOT IN whitelist




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