LINQ to XML:处理不存在的节点?
这可能是一个简单的修复(嗯,可能是),但由于某种原因我就是无法弄清楚。
所以,我有一些看起来像这样的 xml:
XElement xml = XElement.Parse (
@"<Alphabet>
<a name="A" />
<b name="B" />
<d name="D" />
<e name="E" />
</Alphabet>");
所以稍后在我的代码中,我引用了一个可能存在也可能不存在的节点,如下所示:
var name = (from b in xml.Descendants("c")
select b.Attribute("name")).FirstOrDefault().Value;
但是当它不存在时,它不会返回 null 或 "" 它会抛出NullReferenceException:未将对象引用设置为对象的实例。
检查并查看节点是否确实存在于我的 linq 查询中的最佳方法是什么?或者我需要以其他方式检查它是否存在?
This may be a simple fix (well, it probably is) but for some reason I just can't figure it out.
So, I have some xml that looks something like this:
XElement xml = XElement.Parse (
@"<Alphabet>
<a name="A" />
<b name="B" />
<d name="D" />
<e name="E" />
</Alphabet>");
So later in my code, I reference a node that may or may not exist in there like so:
var name = (from b in xml.Descendants("c")
select b.Attribute("name")).FirstOrDefault().Value;
But when it doesn't exist, instead of returning null or "" it throws a NullReferenceException: Object reference not set to an instance of an object.
What's the best way to check and see if a node actually exists in my linq query? Or do I need to check if it exists some other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,你正在选择属性 - 所以只需使用:(
我已将其从查询表达式更改为点表示法,因为查询很简单 - 查询表达式语法实际上并没有给你带来任何东西。)
此解决方案的一个问题:它不区分存在“c”元素但不具有“name”属性,以及首先不存在“c”元素。您需要能够区分吗?
Well, you're selecting the attribute - so just use:
(I've changed it from a query expression to dot notation because the query was trivial - query expression syntax wasn't actually buying you anything.)
One problem with this solution: it doesn't differentiate between there being a "c" element but it not having a "name" attribute, and there not being a "c" element in the first place. Do you need to be able to tell the difference?
我创建了扩展方法来为我做到这一点。
I created extension methods to do that for me.
FirstOrDefault
返回null
或XAttribute
,您可以将其转换为string
以获取值:或
FirstOrDefault
returnsnull
or anXAttribute
which you can cast to astring
to get the value:or
您可以执行以下操作:
或者如果您确实需要该元素:
You can do something like this:
or if you really need the element: