Link to home
Start Free TrialLog in
Avatar of IanPaskin
IanPaskin

asked on

c# xml import file

I'm trying to find an easy way of merging two XML files rather than re-writing the second file, one is a template and the other contains data, here is a simplified version of the xml

template.xml
<?xml version="1.0"?>
<import>
  <doctype>blah</doctype>
  <style_sheet>blah</style_sheet>
<imported_data></imported_data>
</import>

Open in new window


data.xml
<data>
 <products>
  <product>
		<code>abc</code>
		<qty>1</qty>
  </product>
  <product>
		<code>abc</code>
		<qty>1</qty>
  </product>
 </products>
</data>

Open in new window


desired output
<import>
  <doctype>blah</doctype>
  <style_sheet>blah</style_sheet>
     <imported_data>
	<data>
	 <products>
	  <product>
			<code>abc</code>
			<qty>1</qty>
	  </product>
	  <product>
			<code>abc</code>
			<qty>1</qty>
	  </product>
	 </products>
	</data>
 </imported_data>
</import>

Open in new window


I have it sort of working using this but the data file is not inside 'imported_data'  it gets placed after it and before </import>

XmlDocument xmlTemplate = new XmlDocument();
                XmlDocument xmlData = new XmlDocument();

                xmlTemplate.Load(sHeaderFile);
                xmlData.Load(sDataFile);


                XmlNode node = xmlTemplate.ImportNode(xmlData.DocumentElement, true);
                xmlTemplate.DocumentElement.AppendChild(node);

                xmlTemplate.Save("C:\\temp\\output.xml");

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of IanPaskin
IanPaskin

ASKER

Hi Fernando

Perfect... A well commented and explained solution, I did have a quick look at XML Linq before posting the question but not used it before, now seeing your solution it looks a lot more powerful than xmldocument, and what you suggested is almost what I was trying to but not with the right tools..

Thanks...
Not a problem Ian, glad I was able to help.