Thursday, February 9, 2012

C# LINQ to XML select by value

Here's my way to filter values in XML and bind to new XML:

The explanation is based on a "Reminder" application I wrote using VS2010 WPF/C#.

1. The structure of the XML I used:

<Reminders>
  <Reminder Title="Wash dishes" Time="3/24/2012 12:00:00" Status="Active"/>
  <Reminder Title="Feed the fish" Time="4/24/2012 12:00:00" Status="Closed"/>
  <Reminder Title="Walk the dog" Time="5/24/2012 12:00:00" Status="Active"/>
  <Reminder Title="Watch LOTR" Time="5/14/2012 12:00:00" Status="Closed"/>
</Reminders>

2. Select all the "Reminder" nodes with Status="Active"

private void my_xml()
{
    XElement new_xml = new XElement("Reminders");
    
    try
    {
        XElement data = XElement.Load(@"C:\your_path\reminder_data.xml");

        var reminders = from reminder in data.Descendants("Reminder")
                        where reminder.Attribute("Status").Value == "Active"
                        select reminder;

        foreach (var reminder in reminders)
        {
           new_xml.Add(reminder);
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}



No comments:

Post a Comment