Art F
Art F

Reputation: 4202

Merging two System.Xml.XmlDocuments

in .NET I have two System.Xml.XMlDocument objects, the first one looks something like this

<NewDataSet>
 <Table>
  <Table1>
    <Name>Aname</Name>
  <Table1>
  <Table2>
    <Val>value</Value>
  </Table2>
 </Table>
<NewDataSet>

I have a 2nd XML document that looks something like this

<HeaderValues>
   <yearValueH>yearValueH</yearValueH>
   <CalendarEventH>CalendarEventH</CalendarEventH>
  </HeaderValues>

I would like two merge the 2nd document into the first one, after the </Table> tag. So far any attempt to do this resulted in a lot of weird errors, does anyone have any suggestions? (Answer preferably in VB.NET, but C# is ok too).

Some of the things I tried (in VB.NET) include (for all the elements):

Dim yearValueH As XmlNode = xmlA.CreateNode("element","yearValueH","")
yearValueH.InnerText= xmlB.GetElementsByTagName("yearValueH")(0).InnerText

Upvotes: 0

Views: 2680

Answers (2)

user2486709
user2486709

Reputation:

You can use XDocument component for .Net. Follow this link

Upvotes: 1

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

Since you require the solution in XmlDocument then try this:

        string xml1 = "<NewDataSet><Table><Table1><Name>Aname</Name></Table1><Table2><Value>value</Value></Table2></Table></NewDataSet>";
        string xml2 = "<HeaderValues><yearValueH>yearValueH</yearValueH><CalendarEventH>CalendarEventH</CalendarEventH></HeaderValues>";

        var doc1 = new XmlDocument();
        doc1.LoadXml(xml1);

        var doc2 = new XmlDocument();
        doc2.LoadXml(xml2);


        XmlNode newNode = doc1.ImportNode(doc2.DocumentElement, true);
        doc1.DocumentElement.AppendChild(newNode);

Then you can view the new document:

        doc1.InnerXml

Upvotes: 3

Related Questions