2013-02-26 21 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. 如果不属于这两种情况,请以不同方式搜索您需要的内容。
相关问题