简体   繁体   中英

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>

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

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

        }

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM