ArgumentException: 要插入的节点来自不同的文档上下文

问题描述

在这个问题以及其他论坛上搜索过 Stackoverflow,但似乎没有人按照我的方式进行搜索。 我的意思是,在我的代码中,我没有使用 XMLNode,而是使用 XMLElement。

所以,不用多说,我的目的是保存在一个已经存在的 XML 文档中,一个新元素是除根之外的其他现有元素的子元素。

这是我的 XML 文件的示例:

<ROOT>
  <NOT_THIS_ONE>
  </NOT_THIS_ONE>

  <THIS_ONE>
  </THIS_ONE>
</ROOT>

所以,这是我的代码

//XML File
TextAsset repository = Resources.Load("Repository") as TextAsset;

//Create XML Reference
XmlDocument xmlDocument = new XmlDocument();

//Load XML File into XML Reference
xmlDocument.LoadXml(repository.text);

//Root Node
XmlNode statsNode = GetRootNode();

//Get History Node
XmlNode thisOneNode = statsNode.ChildNodes.Item(1);

GetRootNode() 函数是这样的:

//Create Xml Reference
XmlDocument xmlData = new XmlDocument();

//Load Xml File into Xml Reference
xmlData.LoadXml(repository.text);

//Get Root Node
return xmlData.ChildNodes.Item(1);

thisOneNode 将 元素作为节点(至少我认为它是这样做的)。 后来,我这样做:

XmlElement childOfThisOne = xmlDocument.CreateElement("CHILD");

XmlElement pointsSession = xmlDocument.CreateElement("POINTS");
pointsSession.InnerText = points.ToString();

childOfThisOne.AppendChild(pointsSession);

thisOneNode.AppendChild(childOfThisOne);

xmlDocument.Save("Assets/Resources/GamePoints.xml");

我的意图是这样的:

<ROOT>
  <NOT_THIS_ONE>
  </NOT_THIS_ONE>

  <THIS_ONE>
    <CHILD>
      <POINTS>102</POINTS>
    </CHILD>
  </THIS_ONE>
</ROOT>

但我在标题中收到错误:“ArgumentException:要插入的节点来自不同的文档上下文。”

有问题的那一行是:thisOneNode.AppendChild(childOfThisOne);

现在,在我搜索过的地方和找到的文章中,人们使用 XmlNode,甚至使用了 xmlDocument.ImportNode();我也尝试过,但发生了同样的错误。现在,我不知道如何解决这个问题,我请求你的帮助。

感谢您的抽出时间,祝您假期愉快!

解决方法

使用 Xml Linq :

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml = 
                @"<ROOT>
                      <NOT_THIS_ONE>
                      </NOT_THIS_ONE>

                      <THIS_ONE>
                      </THIS_ONE>
                  </ROOT>";

            XDocument doc = XDocument.Parse(xml);

            XElement thisOne = doc.Descendants("THIS_ONE").FirstOrDefault();

            thisOne.Add(new XElement("CHILD",new XElement("POINTS",102)));
            doc.Save("Assets/Resources/GamePoints.xml");
        }
    }
}