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 中所有团队的名称。然后我将提取所有团队的所有统计数据并将它们显示在我的应用程序中。你能帮我解决那个空引用异常吗?

4

4 回答 4

3

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

你可以试试

 _profDoc.Load(_profReader);
_attr =  _profDoc.DocumentElement.Attributes;
于 2010-05-16T14:23:47.357 回答
3

你永远不会初始化_attr. 这是一个空引用。

于 2010-05-16T14:24:13.150 回答
1

正如其他人所说,您必须初始化_attr。

有什么价值?

AXmlAttributeCollection由 . 返回XmlElement.Attributes。如果您想要的是元素的属性,则可以使用该属性。如果你想要的是一个“集合XmlAttribute”而不是强行 a XmlAttributeCollection,你可以这样声明:

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

然后使用ICollection<T>.Add代替Append.

或者,使用 LINQ:

_attr = (from node in Teams
        select node.Attributes["name"]).ToList();
于 2010-05-16T15:05:58.180 回答
0

看起来你从来没有给 分配任何东西_attr,所以它当然会分配给null

于 2010-05-16T14:23:48.003 回答