0

NullReferenceException在尝试读取 xml 文件的属性时遇到了问题——从用户输入定义的元素中读取的属性。

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 回答