2013-07-24 41 views
0

我無法弄清楚如何使用HTML敏捷包遍歷DOM。使用HTML敏捷包遍歷DOM

例如,假設我想找到一個含有id="gbqfsa"的元素。

HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
      doc.LoadHtml(Url); 
      var foo = from bar in doc.DocumentNode.DescendantNodes() 
          where bar.Attributes["id"].Value == "gbqfsa" 
          select bar.InnerText; 

現在我這樣做(上圖),但foo是走出來的null。我究竟做錯了什麼?

編輯:這是我使用的if聲明。我只是測試,看看InnerText元素是否等於「Google搜索」。

if (foo.Equals("Google Search")) 
      { 
       HasSucceeded = 1; 
       MessageBox.Show(yay); 
      } 
      else 
      { 
       MessageBox.Show("kms"); 
      } 
      return HasSucceeded; 
+0

如果執行var'foo = ...'行,'foo'不能爲'null'。它可以是一個空集合,但不是'null'。 –

+0

好吧,當我逐句通過代碼說它是空的。任何想法我做錯了,但? –

+0

你能舉一個不起作用的URL和元素ID的例子嗎? –

回答

1

你應該做的是:

var foo = (from bar in doc.DocumentNode.DescendantNodes() 
      where bar.GetAttributeValue("id", null) == "gbqfsa" 
      select bar.InnerText).FirstOrDefault(); 

你忘FirstOrDefault()來選擇滿足where條件的第一要素。

而且我用GetAttributeValue("id", null)代替Attributes["id"].Value如果某個元素具有id屬性,則不會拋出異常。

+0

快速提示一下,如何在我的'if'語句中測試一個元素是否存在? –

+0

if no element exists,'foo == null'(thanks to [FirstOrDefault()](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.firstordefault.aspx)) –

+0

Yeah 'foo == null'作爲'true'出現。無論生病如何,只要弄清楚。謝謝您的幫助。 –

1

我不認爲foo是走出來的null。更有可能的是,bar.Attributes["id"]對於樹中的一些元素是空的,因爲不是所有的後代節點都具有「id」屬性。我建議使用GetAttributeValue方法,如果找不到該屬性,該方法將返回默認值。

var foo = from bar in doc.DocumentNode.DescendantNodes() 
      where bar.GetAttributeValue("id", null) == "gbqfsa" 
      select bar.InnerText;