0

NullReferenceExceptionxml ファイルの属性を読み取ろうとすると、ユーザー入力によって定義されている要素から読み取る属性が表示されます。

StackTrace は私をこの行にリダイレクトし続けます (マーク付き)

XmlDocument _XmlDoc = new XmlDocument();
_XmlDoc.Load(_WorkingDir + "Session.xml");
XmlElement _XmlRoot = _XmlDoc.DocumentElement;
XmlNode _Node = _XmlRoot.SelectSingleNode(@"group[@name='" + _Arguments[0] + "']");
XmlAttribute _Attribute = _Node.Attributes[_Arguments[1]]; // NullReferenceException

どこでポイントを逃したのですか?ここで欠落している参照は何ですか? 私はそれを理解することはできません...

編集:要素が存在し、属性もそうです(値を含む)

<?xml version="1.0" encoding="utf-8"?>
<session>
 <group name="test1" read="127936" write="98386" />
 <group name="test2" read="352" write="-52" />
 <group name="test3" read="73" write="24" />
 <group name="test4" read="264524" write="646243" />
</session>

詳細説明:_Arguments[]ユーザー入力の分割された配列です。ユーザー例の入力test1_read- と に分割され_Arguments[0] = "test"ます_Arguments[1] = "read"

4

2 に答える 2

1

XmlElement.GetAttributeメソッドを使用する方が良いと思いませんか?これは、XmlElement.HasAttributeを使用して、アクセスを試みる前にチェックを実行できることを意味します。これは間違いなくNullReferenceを回避します。

サンプル

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(_WorkingDir + "Session.xml");
XmlElement xmlRoot = xmlDoc.DocumentElement;
foreach(XmlElement e in xmlRoot.GetElementsByTagName("group"))
{
    // this ensures you are safe to try retrieve the attribute
    if (e.HasAttribute("name")
    { 
        // write out the value of the attribute
        Console.WriteLine(e.GetAttribute("name"));

        // or if you need the specific attribute object
        // you can do it this way
        XmlAttribute attr = e.Attributes["name"];       
        Console.WriteLine(attr.Value);    
    }
}

また、.NETでXmlドキュメントを解析するときにLinqToXmlを使用することを検討することをお勧めします。

于 2009-11-13T09:02:10.280 に答える
0

解析している XML ファイルがない場合、おそらく XPath 式で、//group単にgroup.

于 2009-11-13T08:54:29.993 に答える