There is a good code, but it does a little more:

using System.Xml.Linq; var xml = @"<persons> <person><bd>12.03.1956</bd><fio>Тони Старк</fio><age>40</age></person> <person><bd>12.03.1956</bd><fio>Тони Старк 2</fio><age>41</age></person> <person><bd>12.03.1956</bd><fio>Тони Старк 3</fio><age>42</age></person> </persons>"; var xe = XElement.Parse(xml); foreach (var x in xe.Descendants("fio").ToList()) x.Remove(); 

How to fix it so that if there is no <fio>

 <persons> <person><bd>12.03.1956</bd><fio>Тони Старк</fio><age>40</age></person> <person><bd>12.03.1956</bd>.....................<age>41</age></person> <person><bd>12.03.1956</bd><fio>Тони Старк 3</fio><age>42</age></person> </persons> 

add <fio></fio> within the <person> like so:

 <persons> <person><bd>12.03.1956</bd>ТУТ<fio></fio><age>41</age>ИЛИ_ТУТ <fio></fio></person> </persons> 
  • Then you need to run not by fio but by persons. And inside to look if there is fio then norms, otherwise delete. - Vladimir Paliukhovich
  • On the contrary, if there is no fio, then add - Andrew
  • below, the answer added, really did not understand, why there Remove () - Vladimir Paliukhovich
  • And the closing tag </fio> will be added automatically or how? - Andrei
  • Yes, you insert it as XElement is obtained, the markup itself is created - Vladimir Paliukhovich

2 answers 2

 var emptyPersons = xe.Descendants("person") .Where(person => person.Element("fio") == null); foreach (var person in emptyPersons) person.Add(new XElement("fio", "Jon Skeet")); 
  • I tried this code. Previously, if there was no fio tag in another program, there was an exception, now it is not there, we can conclude that the code works. Thank. Perhaps the second answer is also a working code, but I did not check, Thanks too - Andrew
  • I checked the execution of the code more thoroughly, it is executed, but adds only a closing tag to the end and with a space and a slash from the other side - <fio /> - Andrey
  • @ Andrew - <fio /> is not a closing tag. This is a tag with empty content. So, nothing was inserted into it (in my example, the name John Skeet was inserted). - Alexander Petrov
  • I left like this without the contents of person.Add (new XElement ("fio")); - It is right? - Andrei
  • @Andrey - both written and pasted - empty tag without content. Whether this is correct or not depends on the task. - Alexander Petrov

Why not?

 var xml = @"<persons> <person><bd>12.03.1956</bd><fio>Тони Старк</fio><age>40</age></person> <person><bd>12.03.1956</bd><fio>Тони Старк 2</fio><age>41</age></person> <person><bd>12.03.1956</bd>Тони Старк 3<age>42</age></person> </persons>"; var xe = XElement.Parse(xml); foreach (var x in xe.Descendants("person").ToList()) { if (x.Descendants("fio").Count() == 0) { x.Add(new XElement("fio", "Тонни Старк 3")); } x.Remove(); } 
  • Also working code - Andrey