tags:

views:

60

answers:

2

I generated an xml file like this:

 XElement employees =
        new XElement("Work",
           new XElement("record",
              new XElement("Name", textBox1.Text),
              new XElement("Phone", "206-555-0144"),
              new XElement("Address",
                    new XElement("Street1", "123 Main St"),
                    new XElement("City", "Mercer Island"),
                    new XElement("State", "WA"),
                    new XElement("Postal", "68042")
             )),
             new XElement("record",
              new XElement("Name", "22222"),
              new XElement("Phone", "353245345"),
              new XElement("Address",
                    new XElement("Street1", "sdfain St"),
                    new XElement("City", "asdf Island"),
                    new XElement("State", "QLD"),
                    new XElement("Postal", "54322")
              )),
              new XElement("record",
              new XElement("Name", "Peter"),
              new XElement("Phone", "1234"),
              new XElement("Address",
                    new XElement("Street1", "sd St"),
                    new XElement("City", "cbr"),
                    new XElement("State", "act"),
                    new XElement("Postal", "2600")
              )
          )
      );

Later I wish to add new child node under parent node "record" based on a condition (where name="peter"), something like this:

empFile.Elements().Where(r => (string)r.Element("Name") == "Peter")
                  .Add(new XElement("record",
                           new XElement("Mobile", "3253425"),
                           new XElement("Work", 999999)
                       ));

How can I achieve this?

+1  A: 

You are nearly there, your Where clause returns an IEnumerable<XElement> not a single XElement, so you just need to fix that, i.e. call .Single() or .First() etc

eg:

XElement xe = empFile.Elements().Where(r => (string)r.Element("Name") == "Peter").Single();

xe.Add(new XElement("record", new XElement("Mobile", "3253425"), new XElement("Work", 999999)); 
Tim Jarvis
u have assigned Empfile. elements(). blahblah to xeand xe.add new elements, but i found the empFile has been updated as well, how come?
Kiddo
A: 

As well as Tim's suggestion of using Where followed by Single or First, it's worth knowing that there are overloads of those methods which already take predicates. For example:

empFile.Elements()
       .Single(r => (string) r.Element("Name") == "Peter")
       .Add(...);
Jon Skeet