如何合并用C#两个XmlDocuments两个、XmlDocuments

2023-09-03 00:07:33 作者:开着拖拉机唱情歌

我想通过插入第二个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.