[英]Linq query where clause returning null
This is the XML File I am trying to get the tag Element Posted_Status where Posted_Status has Ready 这是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>
I am having a problem where a linq query is returning null. 我在linq查询返回null时遇到问题。 I am trying to query an XML element.
我正在尝试查询XML元素。 The element name is
Posted_Status
. 元素名称为
Posted_Status
。 The tag value is "Ready". 标签值为“ Ready”。 I am trying to get the tag
Posted_Status
where the Posted_Status is equal to "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;
This execute or calls the query into action and display all the values from the Posted_Status
XML tag where the tag value equals "Ready". 这将执行查询或将查询调用为操作,并显示标记值等于“就绪”的
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;
}
}
You don't need to cast to string in where
clause also you need to compare it against Value like 您不需要在
where
子句中强制转换为字符串,还需要将其与Value进行比较,例如
where exp.Element("Posted_Status").Value == "Ready"
Try: 尝试:
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,
};
For Ouput: 对于Ouput:
foreach (var item in expiration)
{
Console.WriteLine("Timed_On: {0} \r\nTimed_Off: {1}", item.Timed_On, item.Timed_Off );
}
(Its better if you parse the values to a propert DateTime
object) (最好将值解析为适当的
DateTime
对象)
Both your from
and where
read Element("Posted_Status")
. 您的
from
和where
读取Element("Posted_Status")
。
Edit based on updated question, this should be it: 根据更新的问题进行编辑,应该是这样:
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;
You have to read the root element first. 您必须先阅读根元素。 Then you iterate through all "Network" and check the "Posted_Status" value
然后,您遍历所有“网络”并检查“ Posted_Status”值
This will return all "Network" elements that suit the condition 这将返回所有符合条件的“网络”元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.