html agility pack text inside in li

Viewed 30

I am getting data inside <'li> tag like this:

var doc = new HtmlDocument();
doc.LoadHtml(html);
var list = new List<string>(doc.DocumentNode.SelectNodes("//li")
                                            .Select(li => li.InnerText));

but if li has another tag inside like <em> that been ignored. How can I keep everything inside in <li> without using InnerHtml?

thanks

1 Answers

What you want is OuterHtml.
Quoting from MDN:

The outerHTML attribute of the Element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can also be set to replace the element with nodes parsed from the given string.

To only obtain the HTML representation of the contents of an element, or to replace the contents of an element, use the innerHTML property instead.

            var doc = new HtmlDocument();
            doc.LoadHtml(@"
<ul>
    <li>
        <em>item 1</em>
    </li>
    <li>
        <span>item</span> <em>2</em> <br/>
    </li>
</ul>
            ");

            var ul = doc.DocumentNode.Element("ul");
            var lis = ul.Elements("li");
            foreach(var li in lis)
            {
                Console.WriteLine("----------------- inner html -------------------");
                Console.WriteLine(li.InnerText); //prints "Item N" (content only)
                Console.WriteLine("----------------- outer html -------------------");
                Console.WriteLine(li.OuterHtml); //prints <li> + all descending tags + </li>
            }
Related