2010-05-16 48 views
0

我在「_attr.Append(xmlNode.Attributes [」name「]);」上得到NullReferenceException錯誤。代碼中的空引用異常

namespace SMAS 
{ 
class Profiles 
{ 
    private XmlTextReader _profReader; 
    private XmlDocument _profDoc; 

    private const string Url = "http://localhost/teamprofiles.xml"; 
    private const string XPath = "/teams/team-profile"; 

    public XmlNodeList Teams{ get; private set; } 
    private XmlAttributeCollection _attr; 

    public ArrayList Team { get; private set; } 

    public void GetTeams() 
    { 
     _profReader = new XmlTextReader(Url); 
     _profDoc = new XmlDocument(); 

     _profDoc.Load(_profReader); 
     Teams = _profDoc.SelectNodes(XPath); 

     foreach (XmlNode xmlNode in Teams) 
     { 
      _attr.Append(xmlNode.Attributes["name"]); 
     } 
    } 
} 
} 

的teamprofiles.xml文件看起來像

<teams> 
    <team-profile name="Australia"> 
     <stats type="Test"> 
     <span>1877-2010</span> 
     <matches>721</matches> 
     <won>339</won> 
     <lost>186</lost> 
     <tied>2</tied> 
     <draw>194</draw> 
     <percentage>47.01</percentage> 
     </stats> 
     <stats type="Twenty20"> 
     <span>2005-2010</span> 
     <matches>32</matches> 
     <won>18</won> 
     <lost>12</lost> 
     <tied>1</tied> 
     <draw>1</draw> 
     <percentage>59.67</percentage> 
     </stats> 
    </team-profile> 
    <team-profile name="Bangladesh"> 
     <stats type="Test"> 
     <span>2000-2010</span> 
     <matches>66</matches> 
     <won>3</won> 
     <lost>57</lost> 
     <tied>0</tied> 
     <draw>6</draw> 
     <percentage>4.54</percentage> 
     </stats> 
    </team-profile> 
</teams> 

我想在一個ArrayList中提取所有球隊的名字。然後,我將提取所有團隊的所有統計數據,並將其顯示在我的應用程序中。你能幫我介紹一下空引用異常嗎?

+0

兩個小技巧避免的NullReferenceException:1)** **總是初始化領域; 2)**避免**使用'null'。 – 2010-05-18 16:59:23

+0

爲了解決,我做了ReSharper告訴我要做的 foreach(XmlNode xmlNode in Teams) { _attr.Append(xmlNode.Attributes [「name」]); } 我添加了foreach循環之前隊空校驗。 – SMUsamaShah 2010-05-19 10:55:56

回答

3

我不能看到你初始化private XmlAttributeCollection _attr;

你可以嘗試

_profDoc.Load(_profReader); 
_attr = _profDoc.DocumentElement.Attributes; 
+0

我應該如何初始化它?我不能初始化它爲 private XmlAttributeCollection _attr = new XmlAttributeCollection() – SMUsamaShah 2010-05-16 14:27:49

+0

@ LifeH20我已添加代碼 – Pharabus 2010-05-16 14:50:36

0

它似乎並不像你曾經分配什麼_attr,所以當然這將是null

3

您從未初始化_attr。這是一個空引用。

+0

我應該初始化它的值是什麼? – SMUsamaShah 2010-05-16 14:30:14

+0

道歉,我無意中編輯了這個答案,而不是我自己的 – Pharabus 2010-05-16 14:53:21

1

正如其他人所說,你必須初始化_attr。

用什麼樣的價值?

A XmlAttributeCollectionXmlElement.Attributes返回。如果你想要的是一個元素的屬性,你可以使用該屬性。如果你想要的是一個「的XmlAttribute集合」,而不是強行一個XmlAttributeCollection,你可以像這樣把它聲明:

ICollection<XmlAttribute> _attr = new List<XmlAttribute>(); 

然後用ICollection<T>.Add代替Append

或者,使用LINQ:

_attr = (from node in Teams 
     select node.Attributes["name"]).ToList();