2

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
  • 2
    FWIW at this late stage, the plural of summary is summaries. Commented Jul 4, 2017 at 18:04

4 Answers 4

2

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>
Sign up to request clarification or add additional context in comments.

Comments

2

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...

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.