user388969
user388969

Reputation: 341

Insert an XML parent node to an existing xml document

I have an XML document. I am trying to add a parent node to the xml document dynamically. How do i do.

Here is my xml

  <navdefinition>
  <link text="/and" href="/and">
      <link text="Overview" href="/overview"  />
      <link text="Information" href="/fo"/>        
  </link>
  </navdefinition>

I am trying to add node to top of this so that one will be the new parent and one sibling at top

    <navdefinition>
      <link text="NewParent" href="/">
         <link text="Sibling" href="/sibling"/>
         <link text="/and" href="/and">
             <link text="Overview" href="/overview"  />
             <link text="Information" href="/fo"/>
         </link>
      </link>
  </navdefinition>

Upvotes: 2

Views: 3385

Answers (2)

trousyt
trousyt

Reputation: 356

Just create a new parent XElement and set its child content:

var xmlDoc = XDocument.Parse(xml);

var parentElement = new XElement("link", xmlDoc.Root.Elements());
parentElement.SetAttributeValue("text", "NewParent");
parentElement.SetAttributeValue("href", "/");
xmlDoc.Root.ReplaceNodes(parentElement);

Upvotes: 2

jdweng
jdweng

Reputation: 34429

Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication82
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<navdefinition>" +
                  "<link text=\"/and\" href=\"/and\">" +
                      "<link text=\"Overview\" href=\"/overview\"  />" +
                      "<link text=\"Information\" href=\"/fo\"/>" +
                  "</link>" +
                "</navdefinition>";

            XDocument doc = XDocument.Parse(xml);

            XElement navDefinition = doc.Element("navdefinition");
            navDefinition.FirstNode.ReplaceWith(
                new XElement("link", new object[] {
                    new XAttribute("text", "NewParent"),
                    new XAttribute("href", "/"),
                    new XElement("link", new object[] {
                        new XAttribute("text", "Sibling"),
                        new XAttribute("href", "/sibling"),
                        navDefinition.FirstNode
                    })
                })
            );

        }

    }
}

Upvotes: 1

Related Questions