Exporting Data: Creating XML Files using C#
When you want to export data, you can choose formats such as XML or csv for the data files. The XML format is more widely used for its flexibility and is desirable by many systems to be able to process the data. This article explains how to create xml files from C# classes.
Situation: Where would you use it:
– When you have to export data from one system to another system on a different platform
– When you have to setup scheduled jobs to export data
– When you want to keep a backup of key data on a regular basis. Though the database will give (better) alternatives, this technique will help you in shared hosting environments where you may want to keep a good backup of users who have signed up on your site, on a daily basis, for example.
This article touches the following technological aspects:
– C# class library
– Creating XML Schema (XSD)
– Generating C# Class file from XSD
– Generating XML files from C# object using XmlSerializer
Example:
Suppose you have the following data which need to be exported in the form of XML files.
Customers:
CustomerID
CompanyName
ContactName
Address
City
PostalCode
Country
Phone
Fax
Each customer may have one-to-many Orders.
Orders:
OrderID
CustomerID
OrderDate
RequiredDate
ShippedDate
ShipAddress
ShipCity
ShipPostalCode
ShipCountry
To export this data on a daily basis, you would create XML files in the following format:
<Customers>
<CustomerID />
<CompanyName />
…
<Orders>
<OrderID />
<OrderDate />
…
</Orders>
<Orders />
<Orders />
…
</Customers>
<Customers />
<Customers />
…
Here are the steps to create it:
1) Create new project in Visual Studio
2) Add a class library to the project
3) Add a schema (.xsd) file to the class library project
4) Add schema elements. There are different ways in which you can add elements. One simple way is to drag and drop the database tables from the server explorer into the .xsd’s design area (when MySchema.xsd is opened with XML Schema Editor).
For this exercise, add Customers and Orders tables from the Northwind database from the server explorer.
The completed schema will look like this in the designer.
See the project source code to view the XSD code (ie with XML tags)
5) Generate the C# Class from xsd
At the VS Command prompt, enter xsd /c MySchema.xsd. This will create MySchema.cs. Rename it to MySchemaClass.cs, add it to the MyDataLayer class library project, update the namespace of MySchemaClass.cs
If your schema’s top element is named ExportData, (<xs:element name=“ExportData“>) MyDataLayer class will have a class named ExportData (public partial class ExportData).
(I’ve also updated the OrderDate datatype to be string in the generated class, to produce a formatted output in the XML)
6) Create the object from ExportData class and fill the object’s properties with data (from Database or from any other source).
eg:
private ExportData _exportXmlData = new ExportData();
(See the source code for full details).
7) Use the XmlSerializer to create XML files
eg:
FileStream fs = null;
try
{
XmlSerializer serializer = new XmlSerializer(typeof(ExportData));
fs = new FileStream(_fileName, FileMode.Create, FileAccess.Write);
serializer.Serialize(fs, _exportXmlData);
}
catch
{
throw;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
(See the source code for full details).
8 ) Run the project. It will create the XML files containing data, which can be exported (via ftp or saved directly to a shared drive).
A typical customer data in the XML file produced by this example will have the following format:
<Customers>
<CustomerID>2</CustomerID>
<CompanyName>Company Name 2</CompanyName>
<ContactName>Contact Name 2</ContactName>
<City>Dallas 2</City>
<Orders>
<OrderID>2000</OrderID>
<OrderDate>Tuesday, August 19, 2008</OrderDate>
<RequiredDate>2008-08-21T14:33:31.8125-05:00</RequiredDate>
<ShipName>UPS 2</ShipName>
</Orders>
<Orders>
<OrderID>2001</OrderID>
<OrderDate>Tuesday, August 19, 2008</OrderDate>
<RequiredDate>2008-08-21T14:33:31.8125-05:00</RequiredDate>
<ShipName>UPS 2</ShipName>
</Orders>
</Customers>
Source Codes:
Please click here to get the source code link. (I hate spam as much as you do and your email id will never be given to others)
Feel free to comment your thoughts / questions / suggestions below.
Really nice article ! Very informative and all the figures and examples are extremely helpful ! Please write similar articles on other C# and ASP.NET topics .
Chhaya
August 20, 2008
@Chhaya, Thank you very much for the comment!
What are some of the .NET technologies & features your projects use?
vinbhat
August 20, 2008
using this m able to generate xml but how can i map these xml tags with tally xml tags please help me
pradnya
August 28, 2008
@pradnya, Your schema (xsd) should match the schema required by tally. Then the generated xml file will contain the xml tags mapping to tally xml tags. If you have a sample tally xml file, open it in visual studio, go to xml menu and click generate schema. When you use this schema to generate c# class, populate data and generate xml files, its tags should match tally xml tags. Hope this helps.
vinbhat
August 29, 2008
Excellent article it really helps.
But I have one question if you need to add how would I go about specifying that in the xsd or the class?
Pratheek
September 12, 2008
@Pratheek, You can add any new elements similar to the existing elements in the xsd. If you update the xsd, you should regenerate the class. Pls let me know if you have further questions.
vinbhat
September 18, 2008
Thank you very much for the sample.
I actually already have my own code doing pretty much the same thing, just slightly different than yours.
I was running into a small issue and thats why i landed on your article =)
My code is very similar to yours except when it comes to step 7, instead of using a serializer,
i am doing myObjectName.GetXml() and my schema is attached to a namespace. My code works perfect except
I can only get the root element to be prefixed with what I have specified
as the prefix, the children elements are not prefixed.
I also tried your sample, since i needed the output xml to be in memory, i changed your filestream to a string writer.
I also added an xmlSerializerNamespace object to specify the namespace and prefix.
The outputted xml still does not have the correct prefix. If you dont mind, I have two questions.
1. would you happen to have any idea how to add prefix to the child elements using my original approach?
2. is there a reason why you chose xmlSerializer instead of just simple call the getXml method?
Thanks again, look forward to hearing from you.
mango
September 22, 2008
@mango, Thank you for the comment and great questions. When you’ve a dataset, you can use GetXml to keep it simple. When you have a complex schema and lots of business logic, it helps to create a class which can be populated considering different rules, and then use XmlSerializer. About using the prefixes, please see http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializernamespaces.aspx. The sample given at that link produces the xml with prefixes to child elements. Hope you find the solution you are looking for and please drop a line here when you do 🙂
vinbhat
September 22, 2008
Thanks for the code. I appreciate it. I am currently working on a similar project. There is a main database from which data is extracted in xml file, and then using that xml file updated in a secondary replica database. I am now able to generate an xml file with the related records. Could you please let me know how should i go ahead and use the xml to update the secondary database(Ms. Access). It has the same tables and columns as the primary one. I tried generating dataset from the xml file and then using adapters, i tried updating the data tables. But it gave error saying valid insert command required.
My approach can be wrong. I would appreciate if you let me know the correct approach.
Thanks in advance.
sneh
September 22, 2008
Thanks vinbhat for the explanation. As mentioned, i did try using your sample + xmlSerializerNamespace and still was not appending the prefix. I think i might end up transforming it, which doesnt really make sense, there must be a way… Thanks again for your response, off to more research =)
mango
September 23, 2008
Thanks for this article! 🙂
Banksy
September 30, 2008
tahnks for the comment. its very good. now i understand how to use xsd to create xml with exported data.
khifa
October 22, 2008
Thank you for this article, very good. I am currently working on a similar project but I have to create only one XML file with data from different classes.
What would be the correct code with the XmlSerializer. ?
What is
Tom
October 22, 2008
This is one of the best methods and never imagined something like this existed also…..
BUT
I also have an issue like one other anonymous user. it causes “q1:” to go in front of every single element, including the root.
I am not sure if i am doing anything incorrect or is it like this only…Please respond
Pooja
November 6, 2008
@Tom, XmlSerializer produces one XML file for the given class. If you want create one XML file from different classes, I think you have to create a schema and generate a class. Fill that class from the data from your different classes. Then use XmlSerializer on this single class.
vinbhat
November 10, 2008
@Pooja, I think, the prefix comes from the namespace. (http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializernamespaces.aspx). You may update your schema (XSD) and retry. The sample project included in the source code doesn’t produce any prefixes in the generated XML files. Another less efficient way is to use a stream reader and replace the unwanted characters after the xml file is generated.
vinbhat
November 10, 2008
it was best. but what will be the code for reading such files
venus
December 3, 2008
@venus, There are different ways to read such files. Here’s one of them:
Using System.Xml;
XmlDocument doc = new XmlDocument();
doc.Load(@”C:\myfolder\myfile.xml”);
XmlNodeReader reader1 = new XmlNodeReader(doc);
Please see http://support.microsoft.com/kb/307548 for details and other examples.
vinbhat
December 5, 2008
I am lookimg into your example and find it very interesting, only problem is that I cannot get to the code sample for some reason…
Chris Fernandes
January 12, 2009
HI vinbhat
My name is Abhijit.
I am intrested in reading the Data of an XML and putting in it the SQL DataBase( for Interoperability). I have tried using the DataSets ReadXML method to achive the same
But its throwing an exception “Cannot add constraint to DataTable ‘xyz’ which is a child table in two nested relations.”
This was a known issue with .NET.
I want to read the XML Data in Custom Objects.
Can you help me with the same.
Abhijit
February 6, 2009
Hi Thanks for this article. It really helps a lot. Please continue to write.
Bergin
February 6, 2009
Hi,
This is a nice and helpful article. I was wondering if you can compare two XML files and find out if the data is different. For example in the example given, if I create XML file everymonth and find that there is change from previous month to this month for a customer, i would like to create file for only the changed customer. How can we do it? Is there an XML cpmpare functionality?
Thanks
Vijay S
Vijay S
February 6, 2009
Thanks for the article.
The example you have given is very general, and I do not find any difficulty in generating this type of XML file myself.
My requirement is a little different one.
I would be pleased to know; How I can generate an XML file similar to the following:
Any help would be appriciated
Thanks
<visitInformation
mohammad rafeeuddin
February 19, 2009
Thankx for the Article but i want to Import this
xml to tally…can u help me in that case to connect to tally database.
Reshma
March 5, 2009
Thanks it was very helpful for me.
Thanks in million vinbhat.
Sangam Shrestha
March 16, 2009
Hi……its really a nice article!i have followed all steps and got proper output but i want to export this
XML document to tally server…as i have made xml
which is matching to tally sample xml.can u plz
help me in this……
Reshma
March 26, 2009
@Reshma, I haven’t used & dont know much abt Tally. But I found this info (which you might already have) – Tally allows users to Import data from other software’s as well as Export data from Tally to other software’s. Tally allows users to Import and Export in ASCII, SDF and XML formats. XML is now the most widely used format of exporting data in the world. Visit their page: http://www.antraweb.com/TechnologyAdvantage.htm for screen shots & more info.
vinbhat
March 28, 2009
@All, HELP!! I’m not finding time to reply to some of the questions above. If anyone knows the answers, please post a comment here which benefits all. It is much appreciated. Thank you!
vinbhat
March 28, 2009