【问题标题】:Insert an XML parent node to an existing xml document将 XML 父节点插入现有 xml 文档
【发布时间】:2016-03-14 19:14:03
【问题描述】:

我有一个 XML 文档。我正在尝试将父节点动态添加到 xml 文档中。我该怎么办。

这是我的 xml

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

我正在尝试将节点添加到它的顶部,这样一个节点将成为新的父节点,一个兄弟节点位于顶部

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

【问题讨论】:

  • 我看到您还没有编写实际代码来处理输入 XML。现在不要看答案。我相信你可以自己做到这一点。然后看看答案是否可以使用:)

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


【解决方案1】:

只需创建一个新的父 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);

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2020-10-17
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多