- Category: C#
- Published on Wednesday, 18 May 2011 16:11
- Written by Shabdar
- Hits: 26309
In this article, I will show you how you can write simple XML files using C# and ADO.Net dataset. You can use this technique to save data into an XML file instead of a database. This can become very handy if you need to work with a very small amount of data and you don't want to use a database.
Download sample from above link and open it with Visual Studio. I have used Visual Studio 2008 for this sample. You may need to convert this project if you are using higher version of Visual Studio. When you run this sample, you would see Create XML File button on top of the form. Click on it to create a new XML file on C: drive. XML file path is mentioned in text box. You can change this path if you want. Then you can click on Read XML file. This will read XML file that program has just created. This will show you XML data in a grid view. You can modify data in Grid View and click on Save XML file button to save it back to C: drive. To check if modified data was saved, you can click on Clear Grid button and then click Read XML button. Grid should display modified data.
Sourcecode is very easy to understand. I have added comments between code to explain what it does.
Create XML file Button click event
This event first creates a datatable DT with dummy data. Datatable DT is then added to dataset DS. Dataset has a WriteXml() method that writes data to specified path.
Read XML file Button click event
This event read XML data from file specified in txtXMLFilePath text box. Dataset has ReadXml() method that can be used to read XML data into Dataset.
Save XML file Button click event
This event save XML data from Grid to file specified in txtXMLFilePath text box.
Clear Grid Button click event
This event clears data from Grid.
It's easier to read/write data into XML file using Dataset. It has a direct methods available to do that. Structuring data is more easier using datatable and dataset. It's also possible to use XmlReader and XmlWriter classes available in System.XML namespace. But I find it little difficult to use.