Html Agility Pack Xpath

c# html-agility-pack xpath

Question

How can I use this xPath with Html Agility Pack?

xPath:

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

I've tried this 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 extract "Test2 Text" without specific the ul tag in the xPath.

Accepted Answer

You can try using this XPath :

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

//div[@class='test']//text()[normalize-space()] finds all non-empty text nodes within the div. And then, [last()] return only the last node from all found text nodes.

Working demo example (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



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