如何在HTML + HTMLAgilitypack中获取下2个节点 [英] How to get next 2 nodes in HTML + HTMLAgilitypack

查看:238
本文介绍了如何在HTML + HTMLAgilitypack中获取下2个节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的HTML代码中有一个表格:

I have a table in the HTML code below:

<table style="padding: 0px; border-collapse: collapse;">
    <tr>
        <td><h3>My Regional Financial Office</h3></td>
    </tr>
    <tr>
        <td>&#160;</td>
    </tr>
    <tr>
        <td><h3>My Address</h3></td>
    </tr>
    <tr>
        <td>000 Test Ave S Ste 000</td>
    </tr>
    <tr>
        <td>Golden Valley, MN 00000</td>
    </tr>
    <tr>
        <td><a href="javascript:submitForm('0000','0000000');">Get Directions</a></td>
    </tr>
    <tr>
        <td>&#160;</td>
    </tr>
</table>

在包含文本我的地址"的表格行之后,如何获取下2个<tr>标记的内部文本?

How can I get the inner text of the next 2 <tr> tags after the tablerow containing the text "My Address?"

推荐答案

您可以使用以下XPath:

You can use following XPath :

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var tdOfInterests = 
        htmlDoc.DocumentNode
               .SelectNodes("//tr[td/h3[.='My Address']]/following-sibling::tr[position() <= 2]/td");
foreach (HtmlNode td in tdOfInterests)
{
    //given html input in question following code will print following 2 lines:
    //000 Test Ave S Ste 000
    //Golden Valley, MN 00000
    Console.WriteLine(td.InnerText);
}

上述XPath的关键是将following-siblingposition()过滤器一起使用.

The key of above XPath is using following-sibling with position() filter.

更新:

有关此答案中使用的XPath的一些说明:

A bit explanation about the XPath used in this answer :

//tr[td/h3[.='My Address']]

在上面选择具有以下内容的<tr>元素:

above part select <tr> element that has :

    具有子<h3>元素且值等于的
  • <td>元素 我的地址"
  • child <td> element that has child <h3> element with value equals 'My Address'
/following-sibling::tr[position() <= 2]

下一个部分从当前<tr>元素(由上一个XPath部分选择的位置)中选择位置为<= 2的以下<tr>元素

/td

从当前<tr>元素中最后选择子<td>元素

the last part select child <td> element from current <tr> element

这篇关于如何在HTML + HTMLAgilitypack中获取下2个节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆