LINQ到XML零检查属性 [英] Linq To Xml Null Checking of attributes
本文介绍了LINQ到XML零检查属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<books>
<book name="Christmas Cheer" price="10" />
<book name="Holiday Season" price="12" />
<book name="Eggnog Fun" price="5" special="Half Off" />
</books>
我想分析这个使用LINQ和我很好奇别人用什么样的方法来处理特别。我现在的这种工作方式是:
I'd like to parse this using linq and I'm curious what methods other people use to handle special. My current way of working with this is:
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
};
如果有更好的方法来解决这个我不知道。
I am wondering if there are better ways to solve this.
谢谢,
- 贾里德
推荐答案
您可以施放属性到字符串
。如果它不存在,你会得到空
和随后的代码应该检查空
,否则将直接返回值。
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.
试试这个:
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")
};
这篇关于LINQ到XML零检查属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文