2015-05-09 79 views
1

我有以下的HTML代碼,我想解析:HtmlAgilityPack選擇子節點數據

<h3 class='bar'> 
    <a href='http://anysite.com/index.php?showuser=7195' title='Profile view'>THIS_IS_USERNAME</a> 
    &nbsp; 
    <a href='http://anysite.com/index.php?showuser=7195&amp;f=' class='__user __id7195' title='Profile view'> 
     <img src='http://anysite.com/public/style_images/car/user_popup.png' alt='' /> 
    </a> 
</h3> 

我需要在這裏選擇的用戶名(「THIS_IS_USERNAME」),並鏈接到配置文件( 「http://anysite.com/index.php?showuser=7195」)

我可以用下面的代碼選擇頂部H3節點:

List<HtmlNode> resultSearch = HTMLPage.DocumentNode.Descendants() 
       .Where(
         x => x.Name.Equals("h3") 
         && x.Attributes["class"] != null 
         && x.Attributes["class"].Value.Equals("bar")       
        ) 
       .ToList(); 

但我怎麼能得到不是‘H3’節點本身,而是‘一個’內部‘H3’與此屬性鏈接在包含用戶名和鏈接到我需要的配置文件?

回答

1

您可以直接查詢鏈接節點,它的Title屬性非常獨特。

在這種情況下使用XPath可能是簡單的,因爲它處理了所有的中間空的檢查,它只是作爲類型安全的,因爲你的Linq查詢將有很多常量字符串:

var node = HTMLPage.DocumentNode.SelectSingleNode("//hr[@class='Bar']/a[@title='Profile View' and @href"); 
if (node != null) 
{ 
    string link = node.Attributes["href"].Value; 
    string username = node.InnerText; 
} 

你可以使用Linq語法編寫類似的代碼,它首先搜索鏈接標記,然後回溯以找到它的h3父項。這樣,你就不必檢查中間空值):

var node = HtmlPage.DocumentNode.Descendants("a") 
    .Where(a => 
     a.Ascendants("h3") 
      .Any(h3 => 
       h3.Attributes["class"] != null 
       && a.Attributes["class"].Value == "bar" 
      ) 
    ) 
    .Where(a => 
     a.Attributes["title"] != null 
     && a.Attributes["title"].Value == "Profile View" 
     && a.Attributes["href"] != null 
    ) 
    .FirstOrDefault(); 

if (node != null) 
{ 
    string link = node.Attributes["href"].value; 
    string username = node.InnerText; 
} 

或者你可以用它作爲第一<a>子「酒吧」的位置:

// the call to First() will throw an exception if the h3 isn't found. 
// returning an empty HtmlNode will allow you to ignore that 

var node = (HtmlPage.DocumentNode.Descendants("h3") 
    .FirstOrDefault(h => 
      h3.Attributes["class"] != null 
      && a.Attributes["class"].Value == "bar") 
    ) ?? HtmlPage.CreateElement("h3")) 
    .Elements("a").FirstOrDefault(); 

if (node != null) 
{ 
    string link = node.Attributes["href"].value; 
    string username = node.InnerText; 
} 
+0

謝謝!這是我尋找的東西! – Oleksii

+0

儘管最後一部分帶有新的HtmlNode(「h3」)) .Elements(「a」)。FirstOrDefault(); 是有點不清楚,似乎沒有工作 – Oleksii

+0

我認爲這解決了它。 – jessehouwing