Html Agility Pack Xpath

c# html-agility-pack xpath

Question

How can I utilize the HTML Agility Pack with this xPath?

xPath:

//div[@class='test']/(text())[last()]

I tested the following code:

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//div[@class='test']/(text())[last()]"))
            {
                test = node.InnerText();
            }

Html:

<div class="test">
        <ul>
            <li><b>Test1</b>Test1 Text</li>
            <li><b>Test2</b>Test2 Text</li>
        </ul>
    </div>

I need to use the xPath to extract "Test2 Text" without mentioning the ul tag.

1
2
2/19/2016 3:37:58 PM

Accepted Answer

You might try the following XPath:

(//div[@class='test']//text()[normalize-space()])[last()]

//div[@class='test']//text()[normalize-space()] discovers all nodes with non-empty text in thediv . After that,[last()] from all text nodes identified, only the final node will be returned.

working example of a demo (see it online here) :

var html = @"<div class='test'>
<ul>
    <li><b>Test1</b>Test1 Text</li>
    <li><b>Test2</b>Test2 Text</li>
</ul>
";
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
HtmlNode node = doc.DocumentNode.SelectSingleNode("(//div[@class='test']//text()[normalize-space()])[last()]");
Console.WriteLine(node.InnerText);

output:

Test2 Text
4
2/19/2016 3:37:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow