Max
Max

Reputation: 1299

How to cast a Int value from a XML attribute using LINQ-to-XML if the attribute does NOT exist?

How do I assign a value from an attribute to a class if the attribute does NOT exist? Convert.ToInt32 works fine if the attribute exists but when it doesn't exist I was told it is better to use a Cast, but cast wont work with Integers:

string xml = GetXmlContent();
TextReader tr = new StringReader(xml);
XDocument doc = XDocument.Load(tr);
var server = doc.Descendants("server")
   .Select(x => new RunningValueServer
   {
     created            = DateTime.Now,
     productName        = (string)x.Attribute("productName"),
   //nlbHostPriority    = (int)x.Attribute("nlbHostPriority"), //this wont work
     nlbHostPriority    = Convert.ToInt32(x.Attribute("nlbHostPriority").Value),
...

Any ideas? Thank you!

Upvotes: 0

Views: 451

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167696

Which value do you want if the attribute does not exist? You could cast to int? instead of int if that is an option: nlbHostPriority = (int?)x.Attribute("nlbHostPriority").

Or if int? is not an option use nlbHostPriority = (int?)x.Attribute("nlbHostPriority")??0. Of course you can replace the 0 with any integer value you want to assign if the attribute is not present.

Upvotes: 1

Related Questions