Linq To Xml Null 属性检查
<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
};
我想知道是否有更好的方法来解决这个问题。
谢谢,
- 贾里德
<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 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.
Thanks,
- Jared
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将该属性转换为
字符串
。如果不存在,您将得到null
并且后续代码应检查null
,否则将直接返回该值。试试这个:
You can cast the attribute to a
string
. If it is absent you will getnull
and subsequent code should check fornull
, otherwise it will return the value directly.Try this instead:
如何使用扩展方法来封装缺少的属性情况:
请注意,只有当
T
是字符串知道通过 IConvertible 转换为的类型时,这才有效。如果您想支持更一般的转换情况,您可能还需要寻找 TypeConverter。如果类型转换失败,这将引发异常。如果您希望这些情况也返回默认值,则需要执行额外的错误处理。How about using an extension method to encapsulate the missing attribute cases:
Note that this will only work if
T
is a type to which string knows to convert via IConvertible. If you wanted to support more general conversion cases, you may need to look for a TypeConverter, as well. This will throw an exception if the type fails to convert. If you want those cases to return the default as well, you'll need to perform additional error handling.在 C# 6.0 中,您可以使用一元空条件运算符
?.
在您的示例中应用它后,它看起来像这样:
您可以阅读更多 此处部分标题为空条件运算符。
In C# 6.0 you can use monadic Null-conditional operator
?.
After applying it in your example it would look like this:
You can read more here in part titled Null-conditional operators.