0

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?

2
  • Why you use XmlDocument? The Linq2XML is the better option. Commented Mar 31, 2014 at 21:06
  • I'm starting out with xml parsing and have been able to work with XMLDocument easier than LINQtoSQL. Commented Mar 31, 2014 at 21:45

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

Comments

0

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\"");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.