将新孩子添加到当前列表中可能更容易。然后对孩子进行排序。请参阅下面的 xml linq 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XElement newChild = new XElement("Child", new object[] {
new XAttribute("Id", "1"),
new XElement("Reference", new XAttribute("Name", "B1")),
new XElement("Details", new object[] {
new XAttribute("Number", "2"),
new XElement("Detail", new XAttribute("Height","52")),
new XElement("Detail", new XAttribute("Weight","3.25"))
})
});
XDocument doc = XDocument.Load(FILENAME);
XElement branch = doc.Descendants("Branch").FirstOrDefault();
branch.Add(newChild);
List<XElement> orderedChildren = branch.Elements("Child").OrderBy(x => (int)x.Attribute("Id")).ToList();
XElement newBranch = new XElement("Branch", orderedChildren);
branch.ReplaceWith(newBranch);
}
}
}