I have two XmlDocuments that both have a namespace attribute specified. Both documents have the same structure, but contain different data. I can’t seem to get a specific node tree from one document added to the end of the same node tree in a second document. Here is an example of my two documents:
Document #1:
<?xml version="1.0"?>
<rootnode xmlns="http://www.mynamespace.com/Service/2012-06-18">
<node0>
</node0>
<node1>
<Item>
<Id>1</Id>
....
</Item>
<Item>
<Id>2</Id>
....
</Item>
<Item>
<Id>3</Id>
....
</Item>
</node1>
</rootnode>
Document #2
<?xml version="1.0"?>
<rootnode xmlns="http://www.mynamespace.com/Service/2012-06-18">
<node0>
</node0>
<node1>
<Item>
<Id>4</Id>
....
</Item>
<Item>
<Id>5</Id>
....
</Item>
<Item>
<Id>6</Id>
....
</Item>
</node1>
</rootnode>
What I’m wanting to accomplish:
<?xml version="1.0"?>
<rootnode xmlns="http://www.mynamespace.com/Service/2012-06-18">
<node0>
</node0>
<node1>
<Item>
<Id>1</Id>
....
</Item>
<Item>
<Id>2</Id>
....
</Item>
<Item>
<Id>3</Id>
....
</Item>
<Item>
<Id>4</Id>
....
</Item>
<Item>
<Id>5</Id>
....
</Item>
<Item>
<Id>6</Id>
....
</Item>
</node1>
</rootnode>
I’m trying to add all <Item> nodes from one document to the other while maintaining the structure of all other nodes. There are an arbitrary number of <Item> nodes in either of the documents. Each <Item> node has a deep nested number of nodes that describe the Item.
Dim dstdoc As XmlDocument = myobject1.XmlDocument
Dim srcdoc As XmlDocument = myobject2.XmlDocument
Dim nsmgr As New XmlNamespaceManager(New NameTable)
nsmgr.AddNamespace("ns", "http://www.mynamespace.com/Service/2012-06-18")
Dim xpath As String = "ns:rootnode/ns:node1//ns:Item"
Dim copiedNode As XmlNode = dstdoc.ImportNode( _
srcdoc.SelectSingleNode(xpath, nsmgr), True)
dstdoc.DocumentElement().AppendChild(copiedNode)
I certainly know this is wrong… I’ve tried several different approaches. This particular approach adds all <Item> nodes to the destination document, but it adds them to the very bottom of the document instead of after the last <Item>.
Could someone please show me how to add a specific node tree an XmlDocument to a specific position in another document? Again, there is a namespace involved and the <Item> nodes have nested nodes/elements under each one.
NOTE: The <Id> nodes have example data to show uniqueness only. I can never count on any kind of numbering. The order of each <Item> node is totally unimportant. I’m just assuming it will be easiest to add additional <Item> nodes after the last one in the destination document.
You’re close. This line is incorrect:
That is explicitly saying that you want to append to the “document element” (meaning root element). If you want to append to a particular element in the destination document, you’ll first have to get a reference to that target element: