tags:

views:

4397

answers:

4

I'm simply trying to merge 2 xml documents (adding nodes from one into the other). I've done some Google searching, and tried a few things, but I always get the same error "The node to be inserted is from a different document context"

I'm sure I'm missing something simple, just seems like this should not be that difficult.

Here's my code:

    Dim xmlDoc482 As XmlDocument = New XmlDocument
    Dim xmlDoc486 As XmlDocument = New XmlDocument
    Dim xmlDoc490 As XmlDocument = New XmlDocument

    xmlDoc482.LoadXml(strSettlement482)
    xmlDoc486.LoadXml(strSettlement486)
    xmlDoc490.LoadXml(strSettlement490)

    Dim xmlSummarysNode490 As XmlNode = xmlDoc486("Summarys")
    Dim xmlSummaryNode482 As XmlNode = xmlDoc482("Summarys").LastChild
    Dim xmlSummaryNode486 As XmlNode = xmlDoc486("Summarys").LastChild

    Dim nodeDest As XmlNode
    nodeDest = xmlDoc490.ImportNode(xmlSummaryNode482, True)
    xmlSummarysNode490.AppendChild(nodeDest)

    nodeDest = xmlDoc490.ImportNode(xmlSummaryNode486, True)
    xmlSummarysNode490.AppendChild(nodeDest)
+1  A: 

Try appending the imported nodes to the DocumentElement instead of the line Dim xmlSummarysNode490 As XmlNode = xmlDoc486("Summarys").

xmlDoc490.DocumentElement.AppendChild(nodeDest)

You could also try using the CloneNode() instead of ImportNode() before the insertion.

Finally something that helped me in merging in the past was to build a simple container xml then dump the children documents all into it.

xmlMerged.LoadXML("<set></set>")

So it becomes:

<set>
 <Summary>....</Summary>
 <Summary>....</Summary>
 ...
</set>
Mister Lucky
+2  A: 

You could create a helper function (or even better, an extension method) to create a copy of the XML node but changes the node's associated document to the document you want to merge into. You could also try using reflection, but that gets kind of messy...

Zach Johnson
A: 

This works great, other then my stupid, stupid typo

This:

Dim xmlSummarysNode490 As XmlNode = xmlDoc486("Summarys")

Should be This:

Dim xmlSummarysNode490 As XmlNode = xmlDoc490("Summarys")

An element/node must be added using the document you're adding it to.

Dan Williams
+1  A: 

Here is an easy way to merge 2 xmls with the same schema:

Dim x1 As New Dataset
x1.ReadXml(path1)
Dim x2 As New Dataset
x2.ReadXml(path2)

x1.Merge(x2)
x1.WriteXml(path3)

You can probably adapt it to your own situation.

magnifico