2013-02-26 65 views
1

我需要善意簽署任務。我想用htmlaglitypack來計數標籤。我試圖通過使用htmlcollection節點來計數標籤。但得到對象引用未設置爲html集合的實例

"Object reference not set to an instance of an object"

在行foreach條件。他們中的任何一個人能否糾正爲什麼我會這樣的問題?

我的代碼貼在下面:

public void XmlPPC(string rights) 
{ 
    int count = 0; 
    try 
    { 
     MessageBox.Show(rights); 
     using (FileStream fs = File.Open(rights, 
             FileMode.Open, 
             FileAccess.Read, 
             FileShare.ReadWrite)) 
     using (BufferedStream bs = new BufferedStream(fs)) 
     using (StreamReader sr = new StreamReader(bs)) 
     { 
      HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); 
      doc.Load(sr); 

      HtmlNodeCollection right = doc.DocumentNode.SelectNodes("//copyrightLine"); 
      foreach (HtmlNode logan in right) 
      { 
       count = count + 1; 
       MessageBox.Show("cnt" + count.ToString()); 
      } 

      // snip... 
     } 
    } 
    catch (Exception f) 
    { 
     log = log + "\r\n" + f.ToString(); 
    } 
} 
+0

您確定標籤中存在標籤嗎? – ChrisBint 2013-02-26 12:57:14

+0

請參閱:[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – Default 2013-02-26 13:10:23

+0

是的ChrisBint。標籤退出源文件 – Gan 2013-02-27 05:33:21

回答

0

你得到的錯誤:

Object reference not set to an instance of an object.

,因爲這條線:

HtmlNodeCollection right = doc.DocumentNode.SelectNodes("//copyrightLine"); 

將返回null。這隻能發生,因爲沒有元素名爲copyrightLine。請考慮following specification//操作:

Selects nodes in the document from the current node that match the selection no matter where they are.

現在,解決辦法是的幾件事情之一:

  1. 在那裏得到一個名爲copyrightLine的元素。
  2. 修復拼寫錯誤,因爲它可能拼錯。
  3. 如果不屬於這兩種情況,請以不同方式搜索您需要的內容。
相關問題