使用html敏捷包解析html

时间:2013-03-19 14:10:07

标签: c# html html-agility-pack

我想从这个div收集所有标签,但不知道如何用xpath方法以最佳方式执行此操作

<div class="biz_info">
    <h3><a href="/profil/78122/s%C3%B8rby-rehab/">Sørby Rehab</a></h3>
    <table class="string_14">
        <tbody>
            <tr>
               <td>Postadr.:</td> 
               <td class="tab_space">Rognerudveien 8 B, 0681 Oslo</td> 
            </tr>

            <tr>
                <td>Telefon:</td> 
                <td class="tab_space">928 70 700</td>
            </tr>

            <tr>
                <td>Nettside:</td> 
                <td class="tab_space"><a href="http://www.sorby-rehab.no" target="_blank">www.sorby-rehab.no</a></td>
            </tr>
        </tbody>
    </table>
</div>

今天我的代码看起来像这样(但非常糟糕):

 HtmlDocument doc = new HtmlDocument();
doc.Load(new StringReader(result));
HtmlNode root = doc.DocumentNode;

List<string> anchorTags = new List<string>();

foreach (HtmlNode link in root.SelectNodes("//@class=biz_info"))
{
    string att = link.OuterHtml;
    anchorTags.Add(att);
}

xpath的专业人士可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

HtmlDocument html = new HtmlDocument();
html.Load(new StringReader(result));
var anchorTags = html.DocumentNode.SelectNodes("//div[@class='biz_info']//a")
                     .Select(a => a.OuterHtml)
                     .ToList();

这将为您提供锚标签html的列表。如果你只需要网址:

urls = html.DocumentNode.SelectNodes("//div[@class='biz_info']//a[@href!='']")
           .Select(a => a.Attributes["href"].Value)
           .ToList();