Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

linq

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?

like image 962
Kiddo Avatar asked Aug 23 '10 05:08

Kiddo


2 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(...);
like image 145
Jon Skeet Avatar answered Nov 03 '22 07:11

Jon Skeet


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)); 
like image 37
Tim Jarvis Avatar answered Nov 03 '22 07:11

Tim Jarvis