开发者

null reference exception in the code

I am getting NullReferenceException error on "_attr.Append(xmlNode.Attributes["name"]);".

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"]);
        }
    }
}
}

the teamprofiles.xml file looks like

  <teams>
    <team-profile name="Australia">
      <stats type="Test">
        <span>1877-2010</span>
        <matches>721</matches>
        <won>339</won>
     开发者_StackOverflow中文版   <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>

I am trying to extract names of all teams in an ArrayList. Then i'll extract all stats of all teams and display them in my application. Can you please help me about that null reference exception?


I cant see where you initialise private XmlAttributeCollection _attr;

you can try

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


You never initialize _attr. It's a null reference.


As others have said, you have to initialize _attr.

With what value?

A XmlAttributeCollection is returned by XmlElement.Attributes. If what you want is the attributes of an element, you can just use that property. If what you want is a "collection of XmlAttribute" but not forcibly a XmlAttributeCollection, you can declare it like this:

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

And then use ICollection<T>.Add instead of Append.

Or, use LINQ:

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


It doesn't seem like you ever assign anything to _attr, so of course it'll be null.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜