Tuesday, August 16, 2011

How to Read a XML File in C#.Net


Following is the program to create, read and edit a XML file in C#.Net.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace CreateAndReadXMLFileByManishAgrahari
{


    class Employee
    {
        public string XMLFileLocation = @"C:\\Manish_Agrahari.xml";

        static void Main(string[] args)
        {
            Employee objEmp = new Employee();

            objEmp.CreateXMLFile();

            objEmp.ReadAndEditXMLFile();
        }

        protected void CreateXMLFile()
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(XMLFileLocation, settings);
            writer.WriteStartDocument();
            writer.WriteComment("This file is generated by the program.");
            writer.WriteStartElement("Employee");
            writer.WriteElementString("FirstName", "Manish");
            writer.WriteElementString("LastName", "Agrahari");
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();
            writer.Close();
        }

        protected void ReadAndEditXMLFile()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(XMLFileLocation);
            XmlNodeList nodes = doc.GetElementsByTagName("Employee");
            string exportOption = nodes[0].InnerText;
            nodes = doc.GetElementsByTagName("FirstName");
            string fileName = nodes[0].InnerText;
            fileName = fileName.Trim();
            doc.GetElementsByTagName("FirstName").Item(0).InnerText = "This is Update First Name Manish Agrahari";
            nodes = doc.GetElementsByTagName("FirstName");
            fileName = nodes[0].InnerText;
            doc.Save(XMLFileLocation);
        }
       
    }
}


0 comments: