使用敏捷包解析html

我有一个要解析的HTML(见下文)

InBox

From Subject Date
no-reply@somemail.net Hi, Welcome just now
someone@outlook.com sa just now

我需要解析<tr onclick=标签中的链接和

标签中的电子邮件地址。

到目前为止,我想从我的html首次出现电子邮件/链接。

 HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(responseFromServer); 

有人能告诉我它是如何做得好的? 基本上我想要做的是从所述标签中的html获取所有电子邮件地址和链接。

 foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//tr[@onclick]")) { HtmlAttribute att = link.Attributes["onclick"]; Console.WriteLine(att.Value); } 

编辑:我需要将解析后的值成对存储在类(列表)中。 电子邮件(链接)和发件人电子邮件。

 public class ClassMailBox { public string From { get; set; } public string LinkToMail { get; set; } } 

您可以编写以下代码:

 HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(responseFromServer); foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//tr[@onclick]")) { HtmlAttribute att = link.Attributes["onclick"]; ClassMailBox classMailbox = new ClassMailBox() { LinkToMail = att.Value }; classMailBoxes.Add(classMailbox); } int currentPosition = 0; foreach (HtmlNode tableDef in doc.DocumentNode.SelectNodes("//tr[@onclick]/td[1]")) { classMailBoxes[currentPosition].From = tableDef.InnerText; currentPosition++; } 

为了保持这段代码的简单,我假设了一些事情:

  1. 电子邮件始终位于包含onlink属性的tr内的第一个td
  2. 每个带有onlink属性的tr都包含一封电子邮件

如果这些条件不适用,则此代码将不起作用,它可能会抛出一些exception(IndexOutOfRangeExceptions),或者它可能会将链接与错误的电子邮件地址匹配。