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内のすべてのチームの名前を抽出しようとしています。次に、すべてのチームのすべての統計を抽出して、アプリケーションに表示します。そのnull参照例外について教えていただけますか?

4

4 に答える 4

3

どこから始めたらいいのかわからないprivate XmlAttributeCollection _attr;

あなたが試すことができます

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

を初期化することはありません_attr。これはnull参照です。

于 2010-05-16T14:24:13.150 に答える
1

他の人が言っているように、_attrを初期化する必要があります。

どのような価値がありますか?

AXmlAttributeCollectionはによって返されXmlElement.Attributesます。要素の属性が必要な場合は、そのプロパティを使用できます。必要なのが「コレクションXmlAttribute」であるが、強制的にではない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 に答える