简体   繁体   中英

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>
        <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();

似乎您从未给_attr分配任何_attr ,因此它肯定为null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM