如何通过控制 C# 中的属性 ID 在 XML 中添加节点?

how to add node in XML by controlling attribute ID in C#?

我有一个XML这样的

<Root>
  <Branch>
    <Child Id="0">
      <Reference Name="B0"/>
      <Details Number="2">
        <Detail Height="50"/>
        <Detail Weight="3"/>
      </Details>
    </Child>
    <Child Id="2">
      <Reference Name="B2"/>
      <Details Number="2">
        <Detail Height="55"/>
        <Detail Weight="3.5"/>
      </Details>
    </Child> 
  </Branch>
</Root>

我想在Child ID=0的数据块后添加一个Child ID=1的新数据块

将新的 child 添加到当前列表可能更容易。然后对children进行排序。请参阅下面的 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);

        }
    }
}