gpt4 book ai didi

c# - 为什么我不能在 LINQ-To-XML 中选择单个元素?

转载 作者:数据小太阳 更新时间:2023-10-29 02:52:31 26 4
gpt4 key购买 nike

我在选择 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;

这些都不起作用。我不断收到:

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 33:
x => x.Type); Line 34: Line 35:
AttachmentsPath = (from e in mySettings.Descendants("Settings") Line 36:
select e.Element("AttachmentsPath")).SingleOrDefault().Value; Line 37:

我可以看到它已正确加载到 XML 文档中。

我在尝试访问我的 xml 文档中的这个单一设置值时做错了什么?哪种方式才是正确的方式?

最佳答案

因为“MySettings”是根节点,所以它没有名为“MySettings”的后代

尝试

 var AttachmentsPath = (from e in mySettings.Descendants("AttachmentsPath")
select e).SingleOrDefault().Value;

然而,如果没有节点,SingleOrDefault 将返回 null,也许您可​​以尝试这样做更安全

var AttachmentsPathElement = (from e in mySettings.Descendants("AttachmentsPath")
select e).SingleOrDefault();

if(AttachmentsPathElement != null)
{
AttachmentsPath = AttachmentsPathElement.Value;
}

关于c# - 为什么我不能在 LINQ-To-XML 中选择单个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2016171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com