Sep 14 2006

Merging two XML files

Posted by admin under XML

I admit it. I am no XML API guru - while I most of the times are able to get things working with my XML files and feeds it is almost always a trial and error.

XSL transforming is something I have never looked into, so when presented with the task of merging two XML files I took the easy way out - using XmlDocument and trying to export the nodes from one document to another.

First: The task was to merge two RSS files into one. While my two files were slightly different from each other (one them of generated from a "real" blog application and the other from myself) here's how a pretty much RSS file looks:



 <?xml version="1.0" encoding="UTF-8" ?> 
 <rss version="2.0">
 <channel>
  <title>ASPCode.net RRS flow</title> 
  <link>http://www.aspcode.net/articles/default.aspx</link> 
  <description>Articles about ASP.NET, C# and development with Visual Studio</description> 
  <ttl>5</ttl> 
 <item>
  <title>Creating an RSS feed for your ASP.NET site</title> 
  <link>http://www.aspcode.net/articles/l_en-US/t_default/ASP.NET/Creating-an-RSS-feed-for-your-ASP.NET-site_article_277.aspx</link> 
  <guid isPermaLink="true">http://www.aspcode.net/articles/l_en-US/t_default/ASP.NET/Creating-an-RSS-feed-for-your-ASP.NET-site_article_277.aspx</guid> 
  <description>How useful a RSS feed actually is is hard for me to say something about, I personally have a hard time understanding the buzz about blogs (why should that be better than a regular website). While the content people present in blogs might be really good - ...</description> 
  <pubDate>Wed, 30 Aug 2006 13:00:09 GMT</pubDate> 
  </item>

So I had two of these - lets simplify the case and say they are stored on disk - d:\temp\Rss-first.xml and d:\temp\rss2.xml

So basically we should open two XmlDocuments, find all "item" nodes in document 2 and append them as children to the "channel" node of document 1.

And believe it or not. My plan worked! Here's the code:



System.Xml.XmlDocument oDocFirst = new XmlDocument();
oDocFirst.Load("d:\\temp\\rss-first.xml");

System.Xml.XmlDocument oDocSecond = new XmlDocument();
oDocSecond.Load("d:\\temp\\rss2.xml");


//Now we have two documents...
XmlNode oNodeWhereInsert = oDocFirst.SelectSingleNode("/rss/channel");
foreach( XmlNode oNode in oDocSecond.SelectNodes("/rss/channel/item"))
{
	oNodeWhereInsert.AppendChild( oDocFirst.ImportNode(oNode,true) );
}

	
oDocFirst.Save("d:\\temp\\oo.xml");