Search code examples
c#xmllinq-to-xmlxmldocumentxmldataset

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


I have an XML like this

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

I want to add a new block of data for Child ID=1 after Child ID=0 data block


Solution

  • It is probably easier to add the new child to the current list. Then sort the children. See the xml linq code below

    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);
    
            }
        }
    }