Linq To Xml Null Checking of attributes

后端 未结 3 2261
小鲜肉
小鲜肉 2021-02-20 18:34

   
   
   

        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-20 19:32

    You can cast the attribute to a string. If it is absent you will get null and subsequent code should check for null, otherwise it will return the value directly.

    Try this instead:

    var books = from book in booksXml.Descendants("book")
                select new
                {
                    Name = (string)book.Attribute("name"),
                    Price = (string)book.Attribute("price"),
                    Special = (string)book.Attribute("special")
                };
    

提交回复
热议问题