开发者

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

开发者 https://www.devze.com 2023-01-12 11:43 出处:网络
I generated an xml file like this: XElement employees = new XElement(\"Work\", new 开发者_开发知识库XElement(\"record\",

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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消