LINQ中对XML的Nullreference异常 [英] Nullreference exception in linq to xml

查看:64
本文介绍了LINQ中对XML的Nullreference异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI 我需要在linq的帮助下解析动态xml.我不确定某个特定元素是否会出现,但我需要为此编写代码.
如果xml中不存在任何元素,我将获得null引用异常.
谁能告诉我如何克服这个问题.

HI I need to parse dynamic xml with the help of linq. i am not sure whether a pecific element is coming or not but i need to write code for it.
If any element is not present in xml i have get null reference exception.
Can any body tell me how to overcome this problem.

推荐答案

我认为值得一看 ^ ]讨论.

希望对您有所帮助.
I think it is worth to look at Linq to XML --> NULL values[^] discussion.

I hope this helps you well.


您可以始终在XElement上测试null.

You can alway test for null on a XElement.

var result = from book in books.Elements("book")
             where book.Attribute("id") != null && book.Attribute("name") != null
             select new { Name = book.Attribute("name").Value, ISBN = book.Attribute("isbn") == null ? "Missing" : book.Attribute("isbn").Value };



如果缺少属性"isbn",则使用字符串"Missing".



If attribute "isbn" is missing, the string "Missing" is used.


您正在尝试在从未初始化或未明确设置为<的类实例上调用方法或属性c0>.就这样.我可以在任何地方.

您是否在Debugger下运行了它?它会向您显示确切的代码行.如果仍然无法解决问题,请发布代码的相关部分;否则,可能会失败.不要忘记用完整的异常信息指出负责异常的代码行.

—SA
You''re trying to call method or property on the class instance which was never initialized or explicitly set to null. That''s all. I can be anywhere.

Did you run it under Debugger. It would show you exact line of code where it happens. If you still cannot figure out how to fix the problem, post a relevant part of code; don''t forget to indicate the lines of code responsible for exception with full exception information.

—SA


这篇关于LINQ中对XML的Nullreference异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆