Link to home
Start Free TrialLog in
Avatar of DanAtkinson
DanAtkinson

asked on

Check if XAttribute exists inside XElement

Hey experts!

I am working on pulling ASP.NET MVC routes from an external file, and it's going well at the moment. My problem is that I want to be able to return the 'controller' attribute from the 'page' element, or the 'controller' attribute from the 'dir' element (parent of the 'page' element).

The problem is that when this runs, it causes an exception (ArgumentNullException) because I'm trying to retrieve the value of an attribute that doesn't exist.

I realise that, in the snippet, retrieving ControllerName is invalid, but I was trying to highlight what I want to  retrieve.

Any help would be great!

Thanks in advance!
XDocument xDoc = XDocument.Load("urls.xml");
var pages =
  from x in xDoc.Descendants().Elements("page")
  select new
  {
    Name = x.Parent.Attribute("name").Value,
    ControllerName = x.Attribute("controller").Value || x.Parent.Attribute("controller").Value,
    ControllerAction = x.Attribute("action").Value,
    Dir = x.Parent.Attribute("name").Value,
    Url = x.Parent.Attribute("name").Value + "/" + x.Attribute("url").Value,
  };
 
//An example of the urls.xml files is thus:
//
//<urls>
//  <dir name="Cheese" controller="Food"> <!-- Always a 'controller' attr on the 'dir' node -->
//    <page url="mexican.htm" action="mexican" controller="bar" />
//    <page url="cheddar.htm" action="cheddar" /> <!-- Note, no controller attribute here ('controller' attr is optional in 'page' node -->
//    <!--...-->
//  </dir>
//  <dir name="Alcohol" controller="Drink">
//  <!--...-->
//  </dir>
//</urls>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Guess you could try nesting too.  Don't believe there are any restrictions stopping you from repeating an inline if in the true section of the first if for x.Parent.Attribute("controller") == null then set some default if true of x.Parent.Attribute("controller").Value if not.
Avatar of DanAtkinson
DanAtkinson

ASKER

Yep, that's the one! I was checking to see if the attribute value string was null or empty, rather than the attribute itself being null.

How stupid am I! :D

Thanks for your speedy answer!
//INVALID CODE
string.IsNullOrEmpty(x.Attribute("controller").Value) ? x.Parent.Attribute("controller").Value : x.Attribute("controller").Value

Open in new window

You are welcome!