c# – Linq To Xml Null检查属性
发布时间:2020-12-15 06:48:35 所属栏目:百科 来源:网络整理
导读:books book name="Christmas Cheer" price="10" / book name="Holiday Season" price="12" / book name="Eggnog Fun" price="5" special="Half Off" //books 我想使用linq解析这个,我很好奇他人用什么方法来处理特殊的.我目前使用的方法是: var books = fro
<books> <book name="Christmas Cheer" price="10" /> <book name="Holiday Season" price="12" /> <book name="Eggnog Fun" price="5" special="Half Off" /> </books> 我想使用linq解析这个,我很好奇他人用什么方法来处理特殊的.我目前使用的方法是: var books = from 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 }; 我想知道如果有更好的方法来解决这个问题. 谢谢, > Jared 解决方法
您可以将属性转换为字符串.如果它不存在,你将得到null,后续的代码应该检查null,否则它将直接返回值.
改为: 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") }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |