Write to XML File Using C#

by percent20 16. December 2007 12:58

Part 1: Write to XML File Using C#
Part 2: Reading Data from XML File Using C#
Part 3: Delete Data from XML File Using C#

Often times people want to write out information to a file instead of a database. Problem is xml is hard to understand at times and code samples aren't much better. I am going to do 3 or 4 posts on how to do basic interaction with an XML file.

Usually the most important part about using an XML file is first writing to it, but how can you write to it if you don' thave an XML file? Below is a basic XML file I have come up with that we are going to read, write and delete from along with an explantion of the XML file.

The XML File

Contact.xml

The concept behind this xml file is first you have the root node, everthing <> is pretty much refered to a node or element (we will use node). The root node holds EVERYTHING in the xml file and can be your starting point if need be. Next is the contacts node that will hold each individual contact and their information.

Next we get to the meat of the xml file. The contact node. There will be, in the case of this xml file, multiple contact nodes with "Child" nodes. Basically, the contact node will have nodes which contain all the information. I look at xml files kind of like the earth. You have your innercore which is you main information, but it needs to be surrounded by the outercore. Then you have the mantel which surrounds the outercore followed by the crust of the earth, everything is layered. Same with XML I have it pictured in my head in layers and everything needs to be accessed in those layers in order.

Constructor

First, lets look at the constructor of our first class. I usually just create a class that handles all the data read, write, and delete stuff. Lets call it DataAccess.cs. At this point create a basic console project and add a DataAccess.cs class to it, and an xml file with the above xml. Here is the constructor I use to start to start with the xml processing. (note: localpath is cut off because it is long)

DataAccess.cs Constructor

In the above code we have the private datamembers and the constructor. I'll explain the code line by line.

private string _path;
Here we have a string that is going to be use for our full path to the xml file. When I say full path I mean name of the file and the location on the harddrive.  So we could potentially have C:\folder\file.xml
private string _localPath = @"The_Path_to_the_project_folder_with_xml_file_";
In this line we are hardcoding the path to the folder where the xml file resides. Doing it this way in real world applications is bad instead use a configuration file, like an xml file, to get the information and set where the xml file is. Hardcoding paths is bad.
XmlDocument doc;
For this snippet of code you should have a "using System.Xml;" statement in your using directives. What this code is doing is setting up an object that is going to hold our xml information so that we can access that information. In the constructor is where we are going to add all the xml to this object.
public DataAccess(string xmlDocumentName)
This is the constructor that will take in the name of the xml file we want to use. So in the case of our xml file it will be "Contacts.xml".
_path = _localPath + xmlDocumentName;
Here we are populating the full path of the xmlfile with the absolute location and the xml's filename. It might look like C:\XMLProject\bin\debug\Contact.xml if you were to write out what it was.
doc = new XmlDocument();
Here we are initializing this object and allowing it to start being used by the rest of the code.
doc.Load(_path);
And this is our magical line. This takes that xml file that we got the name and location of grabs all of the xml from the file and pops it into the XmlDocument object named doc. With that we are ready to start messing with the XML.

Code to write to an XML file

AddContact() Method

Alright the fun part as arrived actually writing your data out to the xml file. It is actually a fairly simple thing to do once you understand what is going on so lets get started.

public void AddContact(Contact contact)
Just threw a curve ball at you. I have a contact datatype specified as a parameter. This is something that I created. It is a non-static class that has 4 properties in it GUID, Name, Email, PhoneNumber. I'll post the code at the end. I use an object like this for simplicty sake. Instead of passing in 4 or 100 parameters I can pass in an object like contact that can have any number of properties and I only have to pass it alone. Later in the code I think you will understand better.
XmlNode newContact = doc.CreateElement("contact");
Here is where we start building out our planet. We are creating at this point our "OuterCore" which will hold the innercore which is the data we want. This node is going to be what we add to xml file. In the method call of CreateElement we are passing it a string called contact. If you look at the xml file you will see this is the container for the main contents and it is namec contact (note case). You should treat xml as case sensitive.
XmlNode guid = doc.CreateElement("Guid");
XmlNode name = doc.CreateElement("Name");
XmlNode email = doc.CreateElement("Email");
XmlNode phone = doc.CreateElement("PhoneNumber");
Here we are creating more XmlNodes each with their own name that will be in xml file. Next we will actually add the data.
guid.InnerText = System.Guid.NewGuid().ToString();
name.InnerText = contact.Name;
email.InnerText = contact.Email;
phone.InnerText = contact.PhoneNumber;
Here we are setting the InterText property to what is in the contact properties. Think of them as the parameters we passed in. Also note the guid is being created on its own. When we save out the xml file what ever is in the innter text propery will be data stored so you can look at it like this
<Node>InnterText</Node>
Next chunk of code
newContact.AppendChild(guid);
newContact.AppendChild(name);
newContact.AppendChild(email);
newContact.AppendChild(phone);
This code might look a bit confusing, but this is what I call packaging your data into one object. Every XmlNode can have childnodes attached to them. In this case the child nodes are the inner core or the xml at the level below contact node. So we need to package everything together and get it ready to add to the main file. So that is what this code does. It goes to the last element if there is one and adds the node there.
doc.SelectSingleNode("//contacts").AppendChild(newContact);
This is what we have been waiting for adding the data to the xml file. So since we packaged all of our information into the contact node inside the newContact object. All we did here was find the contacts node which is the mantle and attached the outercore to it.
doc.Save(_path);
This is pretty much is easy to guess. It actually saves the data to the xml file for us to use at a later date.

 

The following is a rough idea of how you can visualize what AddContact method is doing as it goes from top to bottom.

Process of AddContact() Method

 

Wrap-Up

I am sure you are wondering why there is a GUID and what is a GUID. First, a GUID is a unique identifier that is created and there is never ever another guid with the same numbers and letters in the exact same order. This is useful to be able to uniquely identify data that there might be repeated information of the same type. So in the case of this xml file we could have a lot of contacts, but what if we wanted to delete a contact? We could delete by name, but what if you have multiple conacts with the same name? or even mulitple contact records of the same name, but differen information and you don't want to delete one of the multiple records. In that case we use the guid to find and delete that record.

I said I would post up the code for to the contact class so here it is.

Contact Class

I just want to re-iterate I am not an expert and need help myself on things. The above is a basic way of doing things to get you started. Please if you know of better way of doing things please feel free to leave a comment with your suggestion and advice. I do this to help others and to learn myself. Thank you for reading and please comeback for part two, retrieving data. In the meantime I am including all my code at the bottom of the post for you to play with it. It is just the cs and xml files. No project files.

XmlAccess.zip (2.22 kb)

kick it on DotNetKicks.com

Tags: ,

Comments

12/16/2007 1:38:22 PM #

trackback

Trackback from DotNetKicks.com

Write to XML File Using C#

DotNetKicks.com

12/17/2007 12:29:06 AM #

ehsan

nice article.

ehsan Iran

12/19/2007 5:34:10 AM #

Michael C. Neel

Hi Lindsey,

Nice article! When tackling this I normally use the System.Xml.Serialization namespace and XmlSerializer.  In short, all it takes is:

XmlSerializer xsContact = new XmlSerializer(typeof(Contact));
xsContact.Serialize(someIOStream, MyInstacneOfContact);

and read back with xsContact.Deserialize.  You can decorate your class (contact) to control how the xml is created, and there are options to get advanced with namespaces and such.  Obviously this works best when you can reasonable expect what the Xml will look like (it does handle missing elements and extra elements in Deserialize pretty well).  The method you cover above provides a finer degree of control, and sometimes that's needed.

Michael C. Neel United States

12/19/2007 7:49:24 AM #

percent20

I eventually want to learn how to do it with serialization. Thanks for the tip on it i'll keep that in mind when I am looking into serialization again. Smile

percent20 United States

12/30/2007 10:57:33 AM #

pingback

Pingback from rtipton.wordpress.com

Weekly Link Post 22 « Rhonda Tipton’s WebLog

rtipton.wordpress.com

1/22/2008 1:06:32 PM #

pingback

Pingback from weblogs.asp.net

I have arrived - Beginnermediate ASP.NET

weblogs.asp.net

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

About the author

Something about the author