Question

i have an Xml that contains two Nodes with the same name Settings as following

<TransSettings>
  <Settings>
    <Force>False</Force>
  </Settings>
  <Settings>
    <Active>True</Active>
  </Settings>
</TransSettings>

i want to merge these two Nodes into one single Node

<TransSettings>
  <Setting>
    <Force>False</Force>
    <Active>True</Active>
  </Setting>
</TransSettings>

Note that the parent Node might contain more than two Settings

Was it helpful?

Solution

var xDoc = XDocument.Load(filename); // or XDocument.Parse(xmlstring);
var elems = xDoc.Descendants("Settings").SelectMany(x => x.Elements()).ToList();
xDoc.Root.RemoveAll();
xDoc.Root.Add(new XElement("Settings", elems));
var newxml = xDoc.ToString();

OUTPUT:

<TransSettings>
  <Settings>
    <Force>False</Force>
    <Active>True</Active>
  </Settings>
</TransSettings>

OTHER TIPS

Here is an example:

XDocument xDoc = XDocument.Load("path");
var transElement = xDoc.Descendants("TransSettings").FirstOrDefault();

if (transElement != null)
{
     var settings = transElement.Descendants("Settings");
     List<XElement> settingElements = new List<XElement>();
     for(int i=0;i<settings.Count;i++)
     {
         settingElements.AddRange(settings[i].Elements());
         settings[i].Remove();
     }
     XElement elem = new XElement("Setting", settingElements);
     transElement.Add(elem);
     xDoc.Save("path");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top