我有一个Xml
,其中包含两个名称为Nodes
Settings
的{{1}}
<TransSettings>
<Settings>
<Force>False</Force>
</Settings>
<Settings>
<Active>True</Active>
</Settings>
</TransSettings>
我想将这两个Nodes
合并为一个Node
<TransSettings>
<Setting>
<Force>False</Force>
<Active>True</Active>
</Setting>
</TransSettings>
请注意,父Node
可能包含两个以上Settings
答案 0 :(得分:1)
以下是一个例子:
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");
}
答案 1 :(得分:1)
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();
输出:
<TransSettings>
<Settings>
<Force>False</Force>
<Active>True</Active>
</Settings>
</TransSettings>