0

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

  • I am creating XmlDocument and trying to add the block there but I do not know how to search for the exact id and add data block after it – Vishal Joshi Mar 08 '21 at 19:07
  • 1
    Can you post the code you're using to parse the xml? – gunr2171 Mar 08 '21 at 19:10
  • Why would the order be relevant? That's not how XML is intended. – Stefan Mar 08 '21 at 19:27
  • @Stefan Actually this is a simplified version of my code. here it is not relevant but in my actual code, it is necessary to have it at its specific position because it is geometry data so it has some reference data which should be there before the upcoming code. – Vishal Joshi Mar 08 '21 at 19:38
  • Does this answer your question? [how to add XElement in specific location in XML Document](https://stackoverflow.com/questions/5725720/how-to-add-xelement-in-specific-location-in-xml-document) – Mohammed Sajid Mar 08 '21 at 20:36

1 Answers1

0

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

        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20