DEV DINNER FOLLOW UP: Introduction to LINQ + LINQ to SQL

Thanks to everyone who attended!  You can download the deck and code from here

A question came up that I did not have time to answer deeper than "Yes, you can do it."  The question was "Can I update XML using LINQ to XML?"  There are two fundamental ways.  The first is to do in-memory XML tree modification using procedural code.  This is similar to how you would update XML using XmlDocument, but instead you would use the new LINQ to XML classes like XElement, XAttribute, etc.  For example, let us work with the following Customers.xml:

 <?xml version="1.0" encoding="utf-8" ?>
<Customers>
  <Customer>
    <ID>ALFKI</ID>
    <Name>Alfred</Name>
    <State>MD</State>
  </Customer>
  <Customer>
    <ID>VMI98</ID>
    <Name>Marc</Name>
    <State>VA</State>
  </Customer>
  <Customer>
    <ID>ALFKO</ID>
    <Name>Alfonso</Name>
    <State>MD</State>
  </Customer>
  <Customer>
    <ID>VMI01</ID>
    <Name>Adam</Name>
    <State>VA</State>
  </Customer>
</Customers>

If we want to append "_UPDATED" to the names of all customers who live in VA, the code would look something like:

 var customers = XElement.Load("Customers.xml");

foreach (var cust in customers.Elements())
{
    var state = cust.Element("State");
    if (state.Value == "VA")
    {
        cust.Element("Name").Value += "_UPDATED";
    }
}

Console.WriteLine(customers.ToString());

The second approach is taking the source XML and creating new XML by transforming it using  a query.  To do the exact same thing above using a transformation query would be quite a bit more code, so I would not personally take the transformation approach.  I'd stick with the above code.  However, let's say our goal was to take Customers.xml, remove all the customers who don't live in VA, and then append "_UPDATED" to their name.  This scenario feels more appropriate for a transformation query such as:

 var customers = XElement.Load("Customers.xml");

var newCustomers =
    from c in customers.Elements()
    where c.Element("State").Value == "VA"
    select new XElement(
        "Customer", new XElement(
            "ID", c.Element("ID").Value), new XElement(
            "Name", c.Element("Name").Value += "_UPDATED"), new XElement(
            "State", c.Element("State").Value)
        );

var newCustomer = new XElement("Customer", newCustomers);

Console.WriteLine(newCustomer.ToString());

Hope this answers the original question from last night!

-Marc