c# - Linq To Xml Null Checking of attributes -


<books>    <book name="christmas cheer" price="10" />    <book name="holiday season" price="12" />    <book name="eggnog fun" price="5" special="half off" /> </books> 

i'd parse using linq , i'm curious methods other people use handle special. current way of working is:

var books = book in booksxml.descendants("book")                         let name = book.attribute("name") ?? new xattribute("name", string.empty)                         let price = book.attribute("price") ?? new xattribute("price", 0)                         let special = book.attribute("special") ?? new xattribute("special", string.empty)                         select new                                    {                                        name = name.value,                                        price = convert.toint32(price.value),                                        special = special.value                                    }; 

i wondering if there better ways solve this.

thanks,

  • jared

you can cast attribute string. if absent null , subsequent code should check null, otherwise return value directly.

try instead:

var books = book in booksxml.descendants("book")             select new             {                 name = (string)book.attribute("name"),                 price = (string)book.attribute("price"),                 special = (string)book.attribute("special")             }; 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -