0

这是我试图获取标签元素 Posted_Status 的 XML 文件,其中 Posted_Status 已就绪

<?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。标记值为“就绪”。我正在尝试获取Posted_StatusPosted_Status 等于“Ready”的标签。

 // 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_StatusXML 标记中标记值等于“Ready”的所有值。

 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;
     }
 }
4

2 回答 2

0

您不需要在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,
       };

对于输出:

foreach (var item in expiration)
{
    Console.WriteLine("Timed_On: {0} \r\nTimed_Off: {1}", item.Timed_On, item.Timed_Off );
}

(如果将值解析为属性DateTime对象会更好)

于 2013-07-31T17:36:11.343 回答
0

你的fromwhere阅读的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”值

这将返回所有符合条件的“网络”元素

于 2013-07-31T18:06:38.247 回答