【发布时间】:2010-01-06 20:57:29
【问题描述】:
在我的 XML 文档中选择单个元素的值时遇到了麻烦
我的文档看起来像
<?xml version="1.0" encoding="utf-8" ?>
<MySettings>
<AttachmentsPath>Test</AttachmentsPath>
<PendingAttachmentsPath>Test2</PendingAttachmentsPath>
</MySettings>
我已尝试执行以下操作:
XElement mySettings = XElement.Load("MySettings.xml");
string AttachmentsPath = (from e in mySettings.Descendants("MySettings")
select e.Element("AttachmentsPath")).SingleOrDefault().Value;
或
XElement mySettings = XElement.Load("MySettings.xml");
string AttachmentsPath = mySettings.Element("AttachmentsPath").Value;
这些都不起作用。我不断收到:
对象引用未设置为 对象的实例。说明:一个 期间发生未处理的异常 当前网络的执行 要求。请查看堆栈跟踪 有关错误的更多信息 以及它起源于代码的位置。
异常详情: System.NullReferenceException:对象 引用未设置为 对象。
来源错误:
第 33 行:
x => x.Type);第 34 行:第 35 行:
AttachmentsPath = (从 e 到 mySettings.Descendants("设置") 第 36 行:
选择 e.Element("AttachmentsPath")).SingleOrDefault().Value; 第 37 行:
我可以看到它正确地加载到了 XML 文档中。
我在尝试访问我的 xml 文档中的这个单一设置值时做错了什么?哪种方式是正确的方式?
【问题讨论】:
标签: c# .net xml linq-to-xml