Tuesday, May 12, 2009

Read and Write from the xml file with C# / ASP.NET

In this article I have created different methods to read and write from the xml files.
Here are two applications one is class library where I have put all the methods to read and write the xml files and another is a web site.

Example-1: Read the xml file

Here is a Config.xml file in the XMLFile folder. The structure of the file is

<?xml version="1.0" encoding="utf-8" ?>
<root>
<!-- site url-->
<SiteUrl> http://www.site.com</SiteUrl>
<!-- file path-->
<FilePath> c:\\myfolder</FilePath>
<!-- domain name-->
<DomainName> mydoman.com</DomainName>
</root> 


Here I have put some comments also. To read this file I have created a class Configure.cs in the class liberary.
To read the element of the xml file I have used the document.GetElementsByTagName() method.

public void GetValues()
{
  XmlDocument document = new XmlDocument();
  XmlNode node = null;
  try
  {
   if (String.IsNullOrEmpty(path))
   {
    return;
   }
  document.Load(path);
  node = document.GetElementsByTagName("SiteUrl").Item(0);
  this.siteUrl = node.InnerText;
  node = document.GetElementsByTagName("FilePath").Item(0);
  this.FilePath = node.InnerText;
  node = document.GetElementsByTagName("DomainName").Item(0);
  this.domainName = node.InnerText;
 }
 catch
 {
  throw;
 }
 finally
 {
  document = null;
  node = null;
 }
}





To write to this file I have created WriteToFile(string filePath, string fileStreamData), where you have to pass the xml file path and data (may be the xml data in string format). For example I have used this function to create the country1. xml file with node "Mydata" in the default.aspx.cs page.


private void WriteToFile()
{
  ReadWriteXMLClassLib.Configure obConfigure = new ReadWriteXMLClassLib.Configure();

  obConfigure.WriteToFile(Server.MapPath("XMLFiles/Country1.xml"), "Mydata");

}


Example-2: Read the xml file

In the previous example there was a no repetition of elements in the file but in this example the xml file structure is different. Here are number of sub nodes or elements (Employee) are more than one and also added the attribute “id” to each sub node.

< ?xml version="1.0" encoding="utf-8" ? >
<?xml version="1.0" encoding="utf-8" ?>
< Employees>
< Employee id="1" >
< Name>Pankaj Saha< /Name>
< Age>26< /Age>
< Address>
< City>Baroda< /City>
< State>Gujaraat< /State>
< /Address>
< /Employee>
< Employee id="2" >
< Name>Sanjay< /Name>
< Age>27< /Age>
< Address>
< City>Baroda< /City>
< State>Gujaraat< /State>
< /Address>
< /Employee>
< /Employees>


To read this xml file I have created a class FileOperataion.cs in the class library. If there is only one Employee node then you can read this node value only with ReadXmlSubNodeValue() method. Since there are multiple nodes that’s why I have used ReadXmlNodeList() method to read all the node list of Employees and then fetch each node of Employees and get the value of each node of Employee through the ReadXmlSubNodeValue() method.



Example-3: Read the xml file

In this example I have used an xml file with the following format

< ?xml version="1.0" encoding="utf-8" ?>
< Countries>
< Country id="1" >India< /Country>
< Country id="2" >US< /Country>
< Country id="3" >Uk< /Country>
< /Countries>



Here each node has an attribute id and each attribute has different values. Now I need to get the node value by their attribute value, for that I have used the ReadXmlNodeList(string fileName, string xmlPath) method to get the node list and then pass each node to ReadXmlSubNodeValue(XmlNode node, string xPath, string attributeName, string attributeValue) method to get values of specific node. For example if you need to get the country which has id=1 then you can use GetCountry(1) method.

private void GetCountry(int countryId)
{
  ReadWriteXMLClassLib.FileOperataion obFileOperataion = new ReadWriteXMLClassLib.FileOperataion();

  XmlNodeList obNodeList = obFileOperataion.ReadXmlNodeList(Server.MapPath("XMLFiles/Country.xml"), "//Countries");

  if (obNodeList != null)
  {
   foreach (XmlNode obNode in obNodeList)
  {
   tdContry.InnerHtml = obFileOperataion.ReadXmlSubNodeValue(obNode, "Country", "id", countryId.ToString());
  }
 }
}



Example-4: Fill gridview from xml file

In this example I have used the country.xml file. You can see in the Example4.aspx page where I have used to read the xml file to the dataset and assigned that dataset to the gridview. To read the xml file I have used the following function

public DataSet GenerateDataSet(string filePath)
{
  DataSet objDataSet = new DataSet();

  objDataSet.ReadXml(filePath);

  return objDataSet;
}



In this function you have to pass the xml file path. You can also pass the xml string, for this you have to use the following function

public DataSet GenerateDataSetWithString(string inputXmlString)
{
  DataSet objDataSet = new DataSet();

  StringReader sr = new StringReader(inputXmlString);

  objDataSet.ReadXml(sr);

  return objDataSet;
}


Example-5: Create and update the xml file

Here I have implemented a product xml file. The format of the xml file is

< ?xml version="1.0" encoding="utf-8"?>
< Items>
< Item>
< Code>101< /Code>
< Name>Product1< /Name>
< Price>100< /Price>
< Qty>12< /Qty>
< /Item>
< Item>
< Code>102< /Code>
< Name>Product2< /Name>
< Price>100< /Price>
< Qty>12< /Qty>
< /Item>
< /Items>



In this example you can add a new item, update the item and delete the items from the xml file.

Example-6: Delete node from xml file / Select Nodes Using XPath Navigation

Whenever you need to delete a node from the xml file, first of all you have to find the node with specified value then delete that node from the file. Here the xml format is


< ?xml version='1.0'?>
< bookstore xmlns="urn:newbooks-schema">
< book genre="novel" style="hardcover">
< title>Book1< /title>
< author>
< first-name>Pankaj< /first-name>
< last-name>Saha< /last-name>
< /author>
< price>19.95< /price>
< /book>
< book genre="novel" style="other">
< title>Book2< /title>
< author>
< first-name>Sanjay< /first-name>
< last-name>Singh< /last-name>
< /author>
< price>11.99< /price>
< /book>
< /bookstore>

public bool DeleteNode(string bookName)
{
  bool isValue = false;

  XmlDocument doc = new XmlDocument();

  try
  {

  string filePath = Server.MapPath("~/XMLFiles/Example6.xml");

  doc.Load(filePath);

  XmlNodeList nodeList;

  XmlNode root = doc.DocumentElement;

  nodeList = root.SelectNodes("descendant::book[title='" + bookName.ToLower() + "']");

  foreach (XmlNode obNode in nodeList)
  {
  root.RemoveChild(obNode);

  break;

  }

  doc.Save(filePath);
 }
 catch
 {
  throw;
 }
 finally
 {
 doc = null;
 }
 return isValue;
}



Example-6: Reading xml file with XmlTextReader

XmlTextReader is the best way when you need to read the xml file without loading the xml file in memory. When you have a very large xml file, which takes lots of time to load in the memory or document object and you need to find or read some values from the xml file then you can use the XmlTextReader class. This will help you to read the xml node value very fast.
Here I am using the Employee.xml file to read the xml file with the help of XmlTextReader class. You need to add the reference of using System.Xml.

 XmlTextReader reader = new XmlTextReader( Server.MapPath(@"~/XMLFiles/Employee.xml"));

 StringBuilder xmlString = new StringBuilder();

 while (reader.Read())
 {
 switch (reader.NodeType)
 {
  case XmlNodeType.Element: // when node is an element
  xmlString.AppendFormat("<" + reader.Name );

  //fetch all the attributes of the node
  while (reader.MoveToNextAttribute())
  {
   xmlString.AppendFormat(" " + reader.Name + "='" + reader.Value + "'");
  }

  xmlString.AppendFormat (">");
  break;
 case XmlNodeType.Text: //fetch the value of xml element
  xmlString.AppendFormat(reader.Value);
 break;
 case XmlNodeType.EndElement: //show the end of the element.
  xmlString.AppendFormat("");

 break;
 }
}

 Response.Write(xmlString.ToString());





Download: