Question

I am trying to read multiple attributes from an xml file using XMLNode, but depending on the element, the attribute might not exist. In the event the attribute does not exist, if I try to read it into memory, it will throw a null exception. I found one way to test if the attribute returns null:

 var temp = xn.Attributes["name"].Value;
 if (temp == null)
 { txtbxName.Text = ""; }
 else
 { txtbxName.Text = temp; }

This seems like it will work for a single instance, but if I am checking 20 attributes that might not exist, I'm hoping there is a way to setup a method I can pass the value to test if it is null. From what I have read you can't pass a var as it is locally initialized, but is there a way I could setup a test to pass a potentially null value to be tested, then return the value if it is not null, and return "" if it is null? Is it possible, or do would I have to test each value individually as outlined above?

Was it helpful?

Solution

You can create a method like this:

public static string GetText(XmlNode xn, string attrName)
{
    var attr = xn.Attributes[attrName];
    if (attr == null). // Also check whether the attribute does not exist at all
        return string.Empty;
    var temp = attr.Value;
    if (temp == null)
        return string.Empty;
    return temp;
}

And call it like this:

txtbxName.Text = GetText(xn, "name");

OTHER TIPS

If you use an XDocument you could just use Linq to find all the nodes you want.

var names = (from attr in doc.Document.Descendants().Attributes()
             where attr.Name == "name"
             select attr).ToList();

If you are using XmlDocument for some reason, you could select the nodes you want using XPath. (My XPath is rusty).

var doc = new XmlDocument();
doc.Load("the file");
var names = doc.SelectNodes("//[Name=\"name\"");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top