2015-02-08 63 views
0

我需要帮助解析HTML文件。我是新的C#和LINQ和一切我试图一直没有提取“链接”全成和“名称1”使用LINQ解析HTML

 <tr class="Row"> 
       <td width="80"> 
       <div align="left"> <a href="link">details</a> 
       </div> 
       </td> 
       <td width="152">Name 1</td> 
       <td width="151">Name 2</td> 
       <td width="152">Name 3</td> 
       <td width="151">Name 4</td> 
       <td width="151">Name 5</td> 
       <td width="152">Name 6</td> 
     </tr> 

     <tr class="Row"> 
       <td width="80"> 
       <div align="left"> <a href="link">details</a> 
       </div> 
       </td> 
       <td width="152">Name 1</td> 
       <td width="151">Name 2</td> 
       <td width="152">Name 3</td> 
       <td width="151">Name 4</td> 
       <td width="151">Name 5</td> 
       <td width="152">Name 6</td> 
     </tr> 

这是我的尝试:

   var links = htmlDoc.DocumentNode.Descendants() 
        .Where(n => n.Name == "tr") 
        .Where(x => x.Attributes["class"] != null && x.Attributes["class"].Value == "Row") 
        .Select(x => x.Descendants() 
        .Where(s => s.Name == "href")); 

       foreach (var link in links) 
       { 
        Debug.WriteLine(link); 
       } 
+0

您是否使用Html Agility Pack? – igorushi 2015-02-08 10:36:54

+0

我使用HtmlAgilityPack-PCL – Macaret 2015-02-08 10:38:02

+0

检查答案,并告诉我,如果有什么不清楚 – mybirthname 2015-02-08 10:42:18

回答

0
var nodes= htmlDoc.DocumentNode.Descendants() 
        .Where(n => n.Name == "a" || 
(n.Name == "td" && n.Attribute["width"] != null && n.Attribute["width"].Value != "80" && n.Parent.Name == "tr" && n.Parent.Attribute["class"] != null && n.Parent.Attribute["class"].Value = "Row")); 


       foreach (var node in nodes) 
       { 
        if(node.Attribute["href"] != null) 
        { 
         Debug.WriteLine(node.Attribute["href"].Value); 
        } 
        else 
        { 
         Debug.WriteLine(node.InnerText); 
        } 
       } 

你需要这样的东西。您正在使用名称为a或每个节点td的节点,其宽度不是80并且tr父节点具有class="Row"

+1

感谢您的帮助 – Macaret 2015-02-08 11:43:53

+0

欢迎您 – mybirthname 2015-02-08 16:31:42

0

您的linq不反映html的结构。 它可以简单地使用xpath来实现。

var links = htmlDoc.DocumentElement 
    .SelectNodes("//tr[class='Row']/td/div/a") 
    .Select(aElem=>aElem.Attributes["href"].Value) 
+0

我无法使用Xpath,因为我的项目是Windows Phone 8.1 – Macaret 2015-02-08 10:53:15