如何向 C# XmlDocument 添加新的根元素?

发布于 2024-08-21 20:05:50 字数 642 浏览 4 评论 0原文

我有一个不受我控制的 XmlDocument,其结构如下:

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

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

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

我需要格式如下的 XmlDocument:

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

我不想制作父母2的副本。如何在不复制parent2的情况下获得我需要的结构?我相信这个手段

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

是不可能的。

有什么好的解决办法吗?

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

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

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

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

I need an XmlDocument in the format:

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

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

is out of the question.

Any good solutions out there?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

养猫人 2024-08-28 20:05:50

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

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

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文