Reader Level:
ARTICLE

Xml - A Simple Database

Posted by Vimal Kandasamy Articles | XML March 03, 2009
Xml can be used for different purposes. But in my programming life, I used it as database alone. I feel very comfortable while using xml as data store for my application, due to its simple structure.
  • 0
  • 0
  • 47557

Xml is very simple data store. It will occupy very less memory almost like a text file. If you learn to utilize xml features, then you can easily manage your data with the help of xml.

 

Xml will reduce your programming burden by its simplicity. There is no chance of difficulty in creation and maintenance of an xml database.

 

All the time, xml gave me a nice experience while handling data. I am very much satisfied with performance of xml. That satisfaction leads me to write this article.

 

In this Article, we are going to see

 

  • How to create an xml file?
  • How to add or write data into an xml file?
  • How to read data from an xml file?
  • How to update a data which is stored in an xml file?
  • How to remove data from an xml file?

We are going to see the answer for above questions briefly. I don't want to go depth. I just want to clarify the basic concepts simply and clearly, by not exceeding few words.

 

I have not used any mechanism or tool or control. It's similar to read and write of a text file. Here I meant database as a simple Xml file, nothing more than that.

 

In order to perform those operations we have several classes in C#. But based on my experience, I strongly recommend XmlDocument class for above all operations.

 

Create

 

XmlTextWriter class is used to create an Xml file. In this, we just specify the filepath and type of xml encoding.after that, we have to create a root element of xml document.

Ex:

We are going to create an xml file with CustomerDetails as root element

 

  1. XmlTextWriter xtw;
  2. xtw = new XmlTextWriter(filepath, Encoding.UTF8);
  3. xtw.WriteStartDocument();
  4. xtw.WriteStartElement("CustomerDetails");
  5. xtw.WriteEndElement();
  6. xtw.Close(); 

Comment for each line

 

  1. //create instance for xmltextwriter.
  2. //assign  file path and encoding
  3. //write start document
  4. //create root element
  5. //end root element
  6. //close file. It is automatically saved.

Note: You have to include System.Xml, System.IO, System.Text Packages in order to use above classes.

 

Output

 

<?xml version="1.0" encoding="utf-8"?>

<CustomerDetails />

 

Write- [insert into database]

 

We can add data into an xml file by just adding child nodes to the root element. In this, we just create some xml elements and append those elements to the root as a child element and save the xml document.

 

Before writing, one thing is very important. All the data stored into the xml file will be treated as String only. So we must convert all data types to string.

 

Ex:

 

We just add a customer "abc" with address as "xyz,india"

 

  1. XmlDocument xd = new XmlDocument();
  2. FileStream lfile = new FileStream(filepath, FileMode.Open);
  3. xd.Load(lfile);
  4. XmlElement cl = xd.CreateElement("Customer");
  5. cl.SetAttribute("Name", "abc");
  6. XmlElement na = xd.CreateElement("Address");
  7. XmlText natext = xd.CreateTextNode("xyz,india");
  8. na.AppendChild(natext);
  9. cl.AppendChild(na);
  10. xd.DocumentElement.AppendChild(cl);
  11. lfile.Close();
  12. xd.Save(filepath);

Comment for each line

 

  1. //object creation for XmlDocument class
  2. //open an xml file using file stream
  3. //load opened file in xml document
  4. //create an xml element
  5. //set attribute for that element
  6. //create an xml element
  7. //create text for xml element
  8. //append address text to address node
  9. //append address node to root element
  10. //append root element to xml document
  11. //close the file stream
  12. //save the xmldocument content to the file

Output

 

<?xml version="1.0" encoding="utf-8"?>

<CustomerDetails>

  <Customer Name="abc">

    <Address>xyz,india</Address>

  </Customer>

</CustomerDetails>

 

Read-[fetch data]

 

We can retrieve data from an xml file using XmlDocument class.here we just retrieve data based on the name of the element.we fetch data as whole and take what we want by navigating through its contents.

 

This reading will return everything as String only.After reading we must convert the data into its original datatype.

 

Ex:

 

Here we just read the address of the customer named as "abc"

 

  1. XmlDocument xdoc= new XmlDocument();
  2. FileStream rfile = new FileStream(path, FileMode.Open);
  3. xdoc.Load(rfile);
  4. String address;
  5. XmlNodeList list = xdoc.GetElementsByTagName("Customer");
  6. for (int i = 0; i < list.Count; i++)
  7. {
  8. XmlElement cl = (XmlElement)xdoc.GetElementsByTagName("Customer")[i];
  9. XmlElement add = (XmlElement)xdoc.GetElementsByTagName("Address")[i];
  10. if ((cl.GetAttribute("Name")) == "abc")
  11. {
  12. address = add.InnerText;
  13. break;
  14. }
  15. }
  16. rfile.Close();

Comment for each Line

 

  1. //creation of XmlDocument class Instance
  2. //create a file stream and open the file to be updated
  3. //load file into xmldocument instance
  4. //create a string variable to store address
  5. //find out the no of elements available in xml file
  6. //navigate through each and every nodes
  7.  
  8. //retrieve the customer node
  9. //retrieve the addresss node
  10. //compare it with node to be read
  11.  
  12. //assign address as innertext of node
  13. //break and get away from the for loop
  14.  
  15.  
  16. //close the file stream

Update- [Updation of field]

 

Updation of data is the simplest process.we just read the required data and modify its content and save it.we just retrieve a field (element) and change its InnerText or Set Its Attributes and Save the xml file.

 

Ex:

 

Here we change the customer name from "abc" to "efgh" and change his address from "xyz,india" to "pqrs,india".

 

  1. XmlDocument xdoc = new XmlDocument();
  2. FileStream up = new FileStream(filepath, FileMode.Open);
  3. xdoc.Load(up);
  4. XmlNodeList list = xdoc.GetElementsByTagName("Customer");
  5. for (int i = 0; i < list.Count; i++)
  6. {
  7. XmlElement cu = (XmlElement)xdoc.GetElementsByTagName("Customer")[i];
  8. XmlElement add = (XmlElement)xdoc.GetElementsByTagName("Address")[i];
  9. if (cu.GetAttribute("Name") == "abc")
  10. {
  11. cu.SetAttribute("Name", "efgh");
  12. add.InnerText = "pqrs,india";
  13. break;
  14. }
  15. }
  16. up.Close();
  17. xdoc.Save(filepath);

Comments for each line

 

  1. //creation of XmlDocument class Instance
  2. //create a file stream and open the file to be updated
  3. //load file into xmldocument instance
  4. //find out the no of elements available in xml file
  5. //navigate through each and every nodes
  6.  
  7. //retrieve the customer node
  8. //retrieve the addresss node
  9. //compare it with node to be changed
  10.  
  11. //set new attribute value
  12. //set new innertext of node
  13. //break and get away from the for loop
  14.  
  15.  
  16. //close the file stream
  17. //save the xml file 

Output

 

<?xml version="1.0" encoding="utf-8"?>

<CustomerDetails>

  <Customer Name="efgh">

    <Address>pqrs,india</Address>

  </Customer>

</CustomerDetails>

 

Remove

 

Removing process is also a simple one. We just navigate through all nodes and finds node needs to be removed and remove it. We just remove the child element from the root element and save it

 

Ex:

 

We just remove the customer named as "efgh".

 

  1. FileStream rfile = new FileStream(filepath, FileMode.Open);
  2. XmlDocument tdoc = new XmlDocument();
  3. tdoc.Load(rfile);
  4. XmlNodeList list = tdoc.GetElementsByTagName("Customer");
  5. for (int i = 0; i < list.Count; i++)
  6. {
  7. XmlElement cl = (XmlElement)tdoc.GetElementsByTagName("Customer")[i];
  8. if (cl.GetAttribute("Name") == "efgh")
  9. {
  10. tdoc.DocumentElement.RemoveChild(cl);
  11. }
  12. }
  13. rfile.Close();
  14. tdoc.Save(filepath);

comment for each line

 

  1. //open a file through file stream
  2. //create Xml Document Instance
  3. //load file
  4. //find no of elements available in XmlDocument
  5. //Iterate through each element
  6.  
  7. //get customer element
  8. //Compare with element to be removed
  9.  
  10. //Remove element from document
  11.  
  12.  
  13. //close stream
  14. //save file

Output

 

<?xml version="1.0" encoding="utf-8"?>

<CustomerDetails>

</CustomerDetails>

 

We have seen all the necessary operations that are needed to create and maintain an xml file [database].

 

Of course, Xml database have some limitations. But up to some level we can run our application with xml as a database for its simplicity. I haven't told anything based on any reference. I said everything based on my own experience.

 

I strongly recommend Xml as database for your applications.

Article Extensions
Contents added by banduz llabanduz on Mar 03, 2010
selamat datang
COMMENT USING

Trending up