C# XML操作中的NullReference
在尝试读取xml文件的属性时,我得到了一个C# XML操作中的NullReference,c#,xml,nullreferenceexception,C#,Xml,Nullreferenceexception,在尝试读取xml文件的属性时,我得到了一个NullReferenceException——从用户输入定义的元素中读取什么属性 StackTrace不断将我重定向到此行(已标记) 我哪里没抓住要点?这里缺少什么参考资料?我想不出来 编辑:元素存在,属性(包括值)也存在 进一步说明:\u Arguments[]是一个用户输入的拆分数组。例如,用户输入test1\u read,它被拆分为\u参数[0]=“test”和\u参数[1]=“read”,如果没有解析的XML文件,我想可能在XPath表达式
NullReferenceException
——从用户输入定义的元素中读取什么属性
StackTrace不断将我重定向到此行(已标记)
我哪里没抓住要点?这里缺少什么参考资料?我想不出来
编辑:元素存在,属性(包括值)也存在
进一步说明:
\u Arguments[]
是一个用户输入的拆分数组。例如,用户输入test1\u read
,它被拆分为\u参数[0]=“test”
和\u参数[1]=“read”
,如果没有解析的XML文件,我想可能在XPath表达式中,您需要指定//组
,而不是简单地指定组
使用该方法不是更好吗?这意味着您可以在尝试访问之前使用进行检查。这肯定会避免空引用
样品
另外,我建议您在.NET中解析Xml文档时查看使用。您可以发布正在解析的Xml文件吗?
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>
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);
}
}