[英]Why can't I select a single element in LINQ-To-XML?
我在選擇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;
這些都不起作用。 我不斷得到:
你調用的對象是空的。 描述:執行當前Web請求期間發生未處理的異常。 請查看堆棧跟蹤,以獲取有關錯誤及其在代碼中起源的更多信息。
異常詳細信息:System.NullReferenceException:未將對象引用設置為對象的實例。
來源錯誤:
第33行:
x => x.Type); 第34行:第35行:
AttachmentsPath =(來自mySettings.Descendants(“ Settings”)中的e)第36行:
選擇e.Element(“ AttachmentsPath”))。SingleOrDefault()。Value; 第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;
}
這可行。
string path = mySettings.Element("AttachmentsPath").Value;
您已經快要在那里了,您所要做的就是指定AttachmentPath所在的根元素。
而已...
string attachmentsPath= mySettings.Root.Element("MySettings")
.Elements("AttachmentsPath").SingleOrDefault().Value;
這是不正確的代碼,一個類的默認值為null
,如果返回default,則會得到一個null引用異常。
SingleOrDefault().Value
第二,如果您的第二種方法不起作用,則很可能意味着您無法正確加載XML文件,或者無法在XML中找到元素“ AttachmentsPath”。
XElement mySettings = XElement.Load("MySettings.xml");
string AttachmentsPath = mySettings.Element("AttachmentsPath").Value;
幾個小時前,我只是在處理類似的事情。 原來,我要搜索的元素不存在。 您的文檔中是否可能沒有名為“ Settings”的元素?
為什么要在XElement中加載文檔? 為什么不使用XDocument?
您可以嘗試以下方法:
XDocument mySettings = XDocument.Load("MySettings.xml");
string AttachmentsPath = mySettings.Root.Element("AttachmentsPath").Value;
請嘗試這種方式。我測試了此代碼,可以正常工作
XDocument xmlDoc = XDocument.Load(fileName);
XElement page = xmlDoc.Descendants("MySettings").FirstOrDefault();
string AttachmentsPath = page.Descendants("AttachmentsPath").First().Value;
string PendingAttachmentsPath= page.Descendants("PendingAttachmentsPath").First().Value;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.