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
- XmlTextWriter xtw;
- xtw = new XmlTextWriter(filepath, Encoding.UTF8);
- xtw.WriteStartDocument();
- xtw.WriteStartElement("CustomerDetails");
- xtw.WriteEndElement();
- xtw.Close();
Comment for each line
- //create instance for xmltextwriter.
- //assign file path and encoding
- //write start document
- //create root element
- //end root element
- //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"
- XmlDocument xd = new XmlDocument();
- FileStream lfile = new FileStream(filepath, FileMode.Open);
- xd.Load(lfile);
- XmlElement cl = xd.CreateElement("Customer");
- cl.SetAttribute("Name", "abc");
- XmlElement na = xd.CreateElement("Address");
- XmlText natext = xd.CreateTextNode("xyz,india");
- na.AppendChild(natext);
- cl.AppendChild(na);
- xd.DocumentElement.AppendChild(cl);
- lfile.Close();
- xd.Save(filepath);
Comment for each line
- //object creation for XmlDocument class
- //open an xml file using file stream
- //load opened file in xml document
- //create an xml element
- //set attribute for that element
- //create an xml element
- //create text for xml element
- //append address text to address node
- //append address node to root element
- //append root element to xml document
- //close the file stream
- //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"
- XmlDocument xdoc= new XmlDocument();
- FileStream rfile = new FileStream(path, FileMode.Open);
- xdoc.Load(rfile);
- String address;
- XmlNodeList list = xdoc.GetElementsByTagName("Customer");
- for (int i = 0; i < list.Count; i++)
- {
- XmlElement cl = (XmlElement)xdoc.GetElementsByTagName("Customer")[i];
- XmlElement add = (XmlElement)xdoc.GetElementsByTagName("Address")[i];
- if ((cl.GetAttribute("Name")) == "abc")
- {
- address = add.InnerText;
- break;
- }
- }
- rfile.Close();
Comment for each Line
- //creation of XmlDocument class Instance
- //create a file stream and open the file to be updated
- //load file into xmldocument instance
- //create a string variable to store address
- //find out the no of elements available in xml file
- //navigate through each and every nodes
-
- //retrieve the customer node
- //retrieve the addresss node
- //compare it with node to be read
-
- //assign address as innertext of node
- //break and get away from the for loop
-
-
- //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".
- XmlDocument xdoc = new XmlDocument();
- FileStream up = new FileStream(filepath, FileMode.Open);
- xdoc.Load(up);
- XmlNodeList list = xdoc.GetElementsByTagName("Customer");
- for (int i = 0; i < list.Count; i++)
- {
- XmlElement cu = (XmlElement)xdoc.GetElementsByTagName("Customer")[i];
- XmlElement add = (XmlElement)xdoc.GetElementsByTagName("Address")[i];
- if (cu.GetAttribute("Name") == "abc")
- {
- cu.SetAttribute("Name", "efgh");
- add.InnerText = "pqrs,india";
- break;
- }
- }
- up.Close();
- xdoc.Save(filepath);
Comments for each line
- //creation of XmlDocument class Instance
- //create a file stream and open the file to be updated
- //load file into xmldocument instance
- //find out the no of elements available in xml file
- //navigate through each and every nodes
-
- //retrieve the customer node
- //retrieve the addresss node
- //compare it with node to be changed
-
- //set new attribute value
- //set new innertext of node
- //break and get away from the for loop
-
-
- //close the file stream
- //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".
- FileStream rfile = new FileStream(filepath, FileMode.Open);
- XmlDocument tdoc = new XmlDocument();
- tdoc.Load(rfile);
- XmlNodeList list = tdoc.GetElementsByTagName("Customer");
- for (int i = 0; i < list.Count; i++)
- {
- XmlElement cl = (XmlElement)tdoc.GetElementsByTagName("Customer")[i];
- if (cl.GetAttribute("Name") == "efgh")
- {
- tdoc.DocumentElement.RemoveChild(cl);
- }
- }
- rfile.Close();
- tdoc.Save(filepath);
comment for each line
- //open a file through file stream
- //create Xml Document Instance
- //load file
- //find no of elements available in XmlDocument
- //Iterate through each element
-
- //get customer element
- //Compare with element to be removed
-
- //Remove element from document
-
-
- //close stream
- //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.