将具有相同名称的节点合并到单个节点

时间:2014-02-01 16:07:53

标签: c# xml xmldocument

我有一个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

2 个答案:

答案 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>