如何合并用C#两个XmlDocuments [英] How to merge two XmlDocuments in C#

查看:193
本文介绍了如何合并用C#两个XmlDocuments的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过插入第二个XML文档到年底合并两个的XmlDocument 秒的现有 XMLDOCUMENT 的C#。这是怎么做的?

I want to merge two XmlDocuments by inserting a second XML doc to the end of an existing Xmldocument in C#. How is this done?

推荐答案

事情是这样的:

foreach (XmlNode node in documentB.DocumentElement.ChildNodes)
{
    XmlNode imported = documentA.ImportNode(node, true);
    documentA.DocumentElement.AppendChild(imported);
}

请注意,这忽略了文档元素B文件本身 - 所以,如果说有不同的元素名称或属性要复制过来,你需要制定出你想要做什么

Note that this ignores the document element itself of document B - so if that has a different element name, or attributes you want to copy over, you'll need to work out exactly what you want to do.

编辑:如果按你的意见,你要嵌入的整个文件A中的B文件的,这是比较容易的:

If, as per your comment, you want to embed the whole of document B within document A, that's relatively easy:

XmlNode importedDocument = documentA.ImportNode(documentB.DocumentElement, true);
documentA.DocumentElement.AppendChild(importedDocument);

这仍然会忽略的东西像B文件的XML声明,如果存在的话 - 我不知道会发生什么,如果你试图导入文件的自身的作为不同的文档的节点,它包括一个XML声明...但我怀疑这会做你想要的。

This will still ignore things like the XML declaration of document B if there is one - I don't know what would happen if you tried to import the document itself as a node of a different document, and it included an XML declaration... but I suspect this will do what you want.

这篇关于如何合并用C#两个XmlDocuments的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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