0

我有一个这样的 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 添加一个新的数据块

4

1 回答 1

0

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

        }
    }
}
于 2021-03-08T21:57:12.430 回答