How to add new node just after parent node in XML

Viewed 67

I am combining three xml documents into one using C# XML and Linq. Before I want to save it as a "Final.xml" I want to add a <New> node under the parent node and at the bottom before the closing parent node.

I have a XML structure like this:

<Main>
   <Action>
      <URL />
   </Action>
   <Execute>
      <URL />
      <MetaData />
   </Execute>
   <Action>
      <URL />
   </Action>
   <Assert>
      <URL />
   </Assert>
</Main>

I want to add a new node under the <Main> node and above the</Main> node. The new Scructure needs to look like this:

<Main>
  <New>
    <Action>
      <URL />
   </Action>
   <Execute>
      <URL />
      <MetaData />
   </Execute>
   <Action>
      <URL />
   </Action>
   <Assert>
      <URL />
   </Assert>
  </New>
</Main>

I've tried code like:

...
var xelem3 = xdoc4.Root.Elements();
xdoc1.Root.LastNode.AddAfterSelf(xelem3);

var Tests = xdoc1.Root.Elements("Test");


foreach (var test in Tests)
  {
    test.AddBeforeSelf(new XElement("New"));
  }

   xdoc1.Save(FinalDoc);

This does not work, It runs but nothing happens. I don't think a loop is the best way and I am wondering is there a better way. I have looked around but I don't seem to find what I am looking for.

2 Answers

Here, I would recommend using XDocument (LINQ to XML) instead of XmlDocument (used with .NET version 3.0 or lower), because it's a much newer and very simple to use.

For more information check this official doc.

And, so, by using XDocument, here is how simple can be the solution:

var doc = XDocument.Parse(@"<Main>
    <Action>
        <URL />
    </Action>
    <Execute>
        <URL />
        <MetaData />
    </Execute>
    <Action>
        <URL />
    </Action>
    <Assert>
        <URL />
    </Assert>
</Main>");

var mainCopy = new XElement(doc.Root.Name); // creating an empty copy of the "Main" node
doc.Root.Name = "New"; // replace the "Main" with "New"

doc = new XDocument(new XElement(mainCopy.Name, doc.Root)); // creating a wrapper XML

Most likely there are far more fancy solutions but. this works:

var xmlstring = "<Root><Child1>1</Child1><Child2>2</Child2><Child3>3</Child3></Root>";
var doc = XDocument.Parse(xmlstring);

var childs = doc.Root.Elements().ToList();
doc.Root.RemoveAll();

var parent = new XElement("Parent");
parent.Add(childs);

doc.Root.Add(parent);
Related