Search code examples
c#xmllinqlinq-query-syntax

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 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. I am trying to query an XML element. The element name is Posted_Status. The tag value is "Ready". I am trying to get the tag Posted_Status where the Posted_Status is equal to "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;

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".

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

Solution

  • You don't need to cast to string in where clause also you need to compare it against Value like

    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:

    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)