Search code examples
c#xmlxmldocument

Merging nodes with the same name to a single node


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


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>