Question

I'm getting a NullReferenceException upon trying to read an attribute of an xml-file - what attribute to read from what element is defined by user-input.

The StackTrace keeps redirecting me to this line (marked)

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

Where did I miss the point? What Reference is missing here? I can't figure it out...

Edit: The element exists and so does the attribute (including a value)

<?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>

Further explanation: The _Arguments[] is a splitted array of the user input. The user e.g. inputs test1_read - that is splitted to _Arguments[0] = "test" and _Arguments[1] = "read"

Was it helpful?

Solution

Would you not be better using the XmlElement.GetAttribute method? This means you can then use the XmlElement.HasAttribute to do a check before you try to access it. This would definitely avoid the NullReference.

Sample

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);    
    }
}

Also I would suggest you have a look at using LinqToXml when parsing Xml documents in .NET.

OTHER TIPS

In absence of the XML file you are parsing, I would guess that maybe in the XPath expression, you need to specify //group instead of simply group.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top