Linq To Xml Null Checking of attributes

后端 未结 3 1737
面向向阳花
面向向阳花 2021-02-20 18:39

   
   
   

        
3条回答
  •  你的背包
    2021-02-20 19:40

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

提交回复
热议问题