Reputation: 13
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
Upvotes: 1
Views: 659
Reputation: 116138
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>
Upvotes: 1
Reputation: 101701
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");
}
Upvotes: 1