[英]Linq query where clause returning null
這是XML文件,我正在嘗試獲取標簽元素“已發布狀態”,其中已發布狀態已就緒
<?xml version="1.0" encoding="utf-8"?>
<Server>
<Network> <---Network is the parent element
<Posted_Status id="10">Ready</Posted_Status>
<Timed_On id="10">7/28/2013 9:32:10 AM</Timed_On>
<Timed_Off id="10">8/28/2013 9:32:10 AM</Timed_Off>
</Network>
</Server>
我在linq查詢返回null時遇到問題。 我正在嘗試查詢XML元素。 元素名稱為Posted_Status
。 標簽值為“ Ready”。 我正在嘗試獲取標簽“已Posted_Status
,其中“已發布狀態”等於“就緒”。
// Query's the tag where the tag equals Ready
IEnumerable<XElement> expiration =
from exp in main.Elements("Posted_Status")
where (string)exp.Element("Posted_Status").Value == "Ready"
select exp;
這將執行查詢或將查詢調用為操作,並顯示標記值等於“就緒”的Posted_Status
XML標記中的所有值。
foreach (string exp in expiration)
{
for (int i = 0; i < IntializedPostStat.Count(); i++)
{
IntializedPostStat[i] = exp.ToString();
lstIntializations.Items.Add("[Posted_Status]......"
+ IntializedPostStat[i].ToString());
break;
}
}
您不需要在where
子句中強制轉換為字符串,還需要將其與Value進行比較,例如
where exp.Element("Posted_Status").Value == "Ready"
嘗試:
var expiration =
from exp in main.Elements("Network")
where exp.Element("Posted_Status").Value.Equals("Ready", StringComparison.CurrentCulture)
select
new
{
Timed_On = exp.Element("Timed_On").Value,
Timed_Off = exp.Element("Timed_Off").Value,
};
對於Ouput:
foreach (var item in expiration)
{
Console.WriteLine("Timed_On: {0} \r\nTimed_Off: {1}", item.Timed_On, item.Timed_Off );
}
(最好將值解析為適當的DateTime
對象)
您的from
和where
讀取Element("Posted_Status")
。
根據更新的問題進行編輯,應該是這樣:
XElement main = XDocument.Load(fi.FullName).Element("Server");
var expiration = from exp in main.Elements("Network")
where exp.Element("Posted_Status").Value == "Ready"
select exp;
您必須先閱讀根元素。 然后,您遍歷所有“網絡”並檢查“ Posted_Status”值
這將返回所有符合條件的“網絡”元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.