Subject: How to merge two xml documents together?
Posted By: NewToXSL Post Date: 6/15/2006 9:48:51 AM
Hello guys,

I am trying to merge two xml documents in VB.NET

I have one xmldocument which has the following xml:

<Allocations>
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
</Allocations>

I have another xml Document which has the following:
<Allocations>
   <Item />
   <Item />
   <Item />
</Allocations>

I want to merge the second xmldocument into the first one.

So I want the following:
<Allocations>
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
</Allocations>


The way I approaced it is as follows:

The first xmldocument is called: xdoc

The second xmldocument is called: xdoc_Selected

Dim xnodeList As XmlNodeList = xdoc_Selected.SelectNodes("//Allocations/Item")
For Each xnode In xnodeList
  xdoc.AppendChild(xnode)
Next

But this was giving me an error.  so I tried this method:

xtempnode = xdoc.ImportNode(xdoc_Selected.DocumentElement, True)
xdoc.DocumentElement.AppendChild(xtempnode)

But this results in the following xml:

<Allocations>
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Item />
   <Allocations>
       <Item />
       <Item />
       <Item />
   </Allocations>
</Allocations>

By the way, I DO NOT want to load the two xml's into a DataSet and then merge them.  I want to do it without DataSet. Please advice me on what I am doing wrong.  Thank you.

Sanch



Reply By: BrianWren Reply Date: 6/15/2006 4:03:19 PM
I think you are just going to have to walk the nodes, and be more rudimentary about it.
Is there an .AppendNode method that is the functional equivalent of .AppendChild?  It looks as if (if there is such a creature) that would do the trick in the specific example you gave.
Reply By: nilzee Reply Date: 8/22/2008 5:28:37 AM
Rather than adding the 'DocumentElement' of the second file try something like:

Dim xnodeList As XmlNodeList = xdoc_Selected.SelectNodes("//Allocations/Item")
For Each xnode In xnodeList
  xdoc.DocumentElement.AppendChild(xdoc.ImportNode(xnode))
Next


Go to topic 33855

Return to index page 1