【发布时间】:2021-03-30 17:48:25
【问题描述】:
我已经在 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();我也试过了,同样的错误发生了。现在,我不知道如何解决这个问题,我请求你帮助解决这个问题。
感谢您抽出宝贵时间,祝您节日快乐!
【问题讨论】:
标签: c# xml argumentexception