how to add/insert conditional node into XML using linq to XML

By | January 12, 2018
Questions:

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?

Answers:

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

Questions:
Answers:

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(...);

Leave a Reply

Your email address will not be published. Required fields are marked *