如何将新的根元素添加到C#XmlDocument? [英] How can I add new root element to a C# XmlDocument?

查看:173
本文介绍了如何将新的根元素添加到C#XmlDocument?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制范围之外,我有一个XmlDocument,其结构如下:

I have, outside of my control, an XmlDocument which has a structure like the following:

<parent1>
...minor amount of data...
</parent1>

我还有另一个XmlDocument,它也不在我的控制范围之内,它具有以下结构:

I have another XmlDocument, also outside of my control, which has the following structure:

<parent2>
..very large amount of data...
</parent2>

我需要以下格式的XmlDocument:

I need an XmlDocument in the format:

<parent1>
...minor amount of data...
<parent2>
..very large amount of data...
</parent2>
</parent1>

我不想复制parent2.在不复制parent2的情况下,如何获得所需的结构?我相信这意味着

I don't want to make a copy of parent2. How can I get the structure I need, without copying parent2? I believe this means

oParent1.DocumentElement.AppendChild(oParent1.ImportNode(oParent2.DocumentElement, true));

是不可能的.

有什么好的解决方案吗?

Any good solutions out there?

推荐答案

只需从parent2 XmlDocument中删除DocumentElement,然后将导入的parent1节点附加到XmlDocument(直接-不添加到DocumentElement),然后重新附加删除的元素parent2节点到导入的parent1节点:

Just remove the DocumentElement from the parent2 XmlDocument, then append the imported parent1 node to the XmlDocument (directly -- NOT to the DocumentElement) and re-append the removed parent2 node to the imported parent1 node:

var p1node = oParent2.ImportNode(oParent1.DocumentElement, true);
var p2node = oParent2.RemoveChild(oParent2.DocumentElement);

oParent2.AppendChild(p1node);
p1node.AppendChild(p2node);

这篇关于如何将新的根元素添加到C#XmlDocument?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆