代码之家  ›  专栏  ›  技术社区  ›  SMUsamaShah

代码中的空引用异常

  •  0
  • SMUsamaShah  · 技术社区  · 15 年前

    我在“_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>
    

    我试图在一个数组中提取所有团队的名字。然后我将提取所有团队的所有统计信息,并将它们显示在我的应用程序中。你能帮我解决那个空引用异常吗?

    4 回复  |  直到 15 年前
        1
  •  3
  •   Pharabus    15 年前

    我看不出你在哪里初始化 private XmlAttributeCollection _attr;

    你可以试试

     _profDoc.Load(_profReader);
    _attr =  _profDoc.DocumentElement.Attributes;
    
        2
  •  3
  •   Pharabus    15 年前

    您从不初始化 _attr . 它是一个空引用。

        3
  •  1
  •   R. Martinho Fernandes    15 年前

    正如其他人所说,你必须初始化属性。

    有什么价值?

    XmlAttributeCollection 被返回 XmlElement.Attributes . 如果您想要的是元素的属性,那么只需使用该属性。如果你想要的是 XmlAttribute “但不是强行 XML属性集合 ,您可以这样声明:

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

    然后使用 ICollection<T>.Add 而不是 Append .

    或者,使用LINQ:

    _attr = (from node in Teams
            select node.Attributes["name"]).ToList();
    
        4
  •  0
  •   Joren    15 年前

    你好像从来没有给 _attr ,所以当然是 null .