将XML父节点插入现有xml文档

时间:2016-03-14 19:14:04

标签: c# .net xml sharepoint xml-parsing

我有一个XML文档。我试图动态地将父节点添加到xml文档。我该怎么办。

这是我的xml

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

我正在尝试将节点添加到此顶部,以便其中一个将成为新父级,一个兄弟位于顶部

          // Create the email message
          HtmlEmail email = new HtmlEmail();

          email.setHostName(smtpHost);

          email.setAuthenticator(new DefaultAuthenticator(smtpUser, smtpPwd));

          email.setSSLOnConnect(true);

          email.addTo(to);

          email.setFrom(from);

          email.setSubject(subject);

          // set the html message
          email.setHtmlMsg(text);

          // set the alternative message
          email.setTextMsg("Your email client does not support HTML messages");

          // send the email
          email.send();

2 个答案:

答案 0 :(得分:2)

只需创建一个新的父XElement并设置其子内容:

var xmlDoc = XDocument.Parse(xml);

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

答案 1 :(得分:1)

试试这个

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

        }

    }
}