ARTICLE

Read XML in C#

Posted by Prashanth Chindam Articles | XML September 24, 2010
In this article we will see how to read an Xml file using C#.Net.
Reader Level:
Download Files:
 

1.gif

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace xmlapp
{
    public partial class studdata : Form
    {  
        public studdata()
        {
            InitializeComponent();
        }
        DataSet ds;  string dir;  int rno = 0;
        private void studdata_Load(object sender, EventArgs e)
        {
             ds = new DataSet();
             searchbtn.Enabled = firstbtn.Enabled = prevbtn.Enabled = nextbtn.Enabled = lastbtn.Enabled =clearbtn.Enabled= false;
        }
        private void loadbtn_Click(object sender, EventArgs e)
        {
            try
            {   searchbtn.Enabled = firstbtn.Enabled = prevbtn.Enabled = nextbtn.Enabled = lastbtn.Enabled = clearbtn.Enabled = false;
                ds.Clear(); //for clearing grid view
                dataGridView1.DataSource = null;
                sno_txtbx.Text = sname_txtbx.Text = course_txtbx.Text = fee_txtbx.Text = "";
                pictureBox1.Image = null;
                openFileDialog1.Filter = "xml|*.xml|all files|*.*";
                DialogResult res = openFileDialog1.ShowDialog();
                if (res == DialogResult.OK)
                {  string fpath = openFileDialog1.FileName;
                    ds.ReadXml(fpath);              
                    //setting primary key inorder to search a record using finding method
                    ds.Tables[0].Constraints.Add("pk_sno", ds.Tables[0].Columns[0], true);
                    dataGridView1.DataSource = ds.Tables[0];
                    dir = fpath.Substring(0, fpath.LastIndexOf("\\") + 1);
                    showdata();
                }
            }
            catch
            { MessageBox.Show("invalid input");  }
        }
        void showdata()
        { 
            if (ds.Tables[0].Rows.Count > 0)
            {  searchbtn.Enabled = firstbtn.Enabled = prevbtn.Enabled = nextbtn.Enabled = lastbtn.Enabled = clearbtn.Enabled = true;
                pictureBox1.Image = null;
                sno_txtbx.Text = ds.Tables[0].Rows[rno][0].ToString();
                sname_txtbx.Text = ds.Tables[0].Rows[rno][1].ToString();
                course_txtbx.Text = ds.Tables[0].Rows[rno][2].ToString();
                fee_txtbx.Text = ds.Tables[0].Rows[rno][3].ToString();
                pictureBox1.ImageLocation = dir + ds.Tables[0].Rows[rno][4].ToString();
            }
            else
                MessageBox.Show("No records");
        }
        private void searchbtn_Click(object sender, EventArgs e)
        {  
            int n = Convert.ToInt32(Interaction.InputBox("Enter sno to search:", "Search", "10", 200, 200));
            //searching using find method
            DataRow drow = ds.Tables[0].Rows.Find(n);
            if (drow != null)
            {  rno= ds.Tables[0].Rows.IndexOf(drow);
                sno_txtbx.Text = drow[0].ToString();
                sname_txtbx.Text = drow[1].ToString();
                course_txtbx.Text = drow[2].ToString();
                fee_txtbx.Text = drow[3].ToString();
                pictureBox1.ImageLocation = dir + drow[4];
            }
            else
                MessageBox.Show("record not found");
         }
        private void clearbtn_Click(object sender, EventArgs e)
        { 
            sno_txtbx.Text=sname_txtbx.Text =course_txtbx.Text =fee_txtbx.Text = "";
            pictureBox1.Image = null;
        }
        private void firstbtn_Click(object sender, EventArgs e)
        {
            rno = 0;
            showdata();
        }
        private void prevbtn_Click(object sender, EventArgs e)
        {
            if (rno > 0)
            {
                rno--;
                showdata();
            }
            else
            { MessageBox.Show("first record"); }
        }
        private void nextbtn_Click(object sender, EventArgs e)
        {
            if (rno < ds.Tables[0].Rows.Count - 1)
            {
                rno++;
                showdata();
            }
            else
            { MessageBox.Show("LastRecord"); }
        }
        private void lastbtn_Click(object sender, EventArgs e)
        {
            rno = ds.Tables[0].Rows.Count - 1;
            showdata();
        }
        private void exitbtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }    
    }
}

Note:

Goto Project Menu

->Add Reference -> select 'Microsoft.VisualBasic' from .NET tab; include namespace 'using Microsoft.VisualBasic'(To get input box)

Add OpenFileDialog control to the form, which appears below the form

Add PictureBox Control and change properties as following:

   ->BorderStyle=Fixed3D; SizeMode=StrechImage 

Example for Creating an xml file:

Open notepad and type the following & save it with extension .xml

<students>
  <student>
    <sno>10</sno>
    <sname>Prashanth</sname>
    <course>dotnet</course>
    <fee>3500</fee>
    <photo>prash.jpg</photo>
  </student>
  <student>
    <sno>20</sno>
    <sname>Satyapal</sname>
    <course>java</course>
    <fee>3000</fee>
    <photo>satya.jpg</photo>
  </student>
  <student>
    <sno>30</sno>
    <sname>Mahender</sname>
    <course>php</course>
    <fee>2500</fee>
    <photo>mahi.jpg</photo>
  </student>
</students>

Note: xml file and respective jpeg images should be in same folder 

To execute program click loadxml button and select xml file.

Login to add your contents and source code to this article
post comment
     

Good One

Posted by Gohil Jayendrasinh May 14, 2012

hey man, thank you for providing us with this awesome code. I don't know much, but I usually take for ever to do this kind of thing, now its easy to learn from what is more likely to be obvious.

Posted by thiago costa Sep 26, 2011

Hi Prashanth First thnaks you for this great article. I've read it and tried to adapt to my own xml schema. This is a fragment of my xml file("Carrusel.xml") <Datos> <dato img_Url="images/galeria/foto_1.png" page_Url="http://www.atesa.es/webcorporativa/paginas/ofertas1.aspx" /> . . </Datos> And this is the code to write(to intend) a new node. void InsertItems(String sImagenUrl, String sPaginaUrl) { String rootPath = Server.MapPath("~"); String archivoXmlPath = Path.Combine(rootPath, "Xml//Carrusel.xml"); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(archivoXmlPath); XmlElement dato = xmlDoc.CreateElement("dato"); XmlAttribute imgenUrl = xmlDoc.CreateAttribute("img_Url"); XmlAttribute paginaUrl = xmlDoc.CreateAttribute("page_Url"); imgenUrl.InnerText = sImagenUrl; paginaUrl.InnerText = sPaginaUrl; dato.AppendChild("dato"); imgenUrl.InsertAfter("img_Url", "dato"); paginaUrl.InsertAfter("page_Url", "dato"); xmlDoc.DocumentElement.AppendChild("dato"); xmlDoc.Save(archivoXmlPath); } But I received errors. Where is the bug?. Thanks in advanced. Arsenio

Posted by Arsenio Madrazo Mar 29, 2011

Code for inserting, updating, deleting records in xml file:


we can perform these operations in two ways:

i)performing operations on xml file and saving changes, which includes
   creating xml elements(tags), assigning values, appending them to xml root element,...
   (for this we have to include namespace 'using System.Xml')

ii)performing operations on dataset and saving to xml file

Here, I will show inserting code in two ways; updating and  deleting codes using second method.


Insert Code:

i)    XmlDocument doc = new XmlDocument();
           doc.Load(openFileDialog1.FileName);

            XmlElement root = doc.CreateElement("student")
            XmlElement sno = doc.CreateElement("sno");
            XmlElement sname = doc.CreateElement("sname");
            XmlElement course = doc.CreateElement("course");
            XmlElement fee = doc.CreateElement("fee");
            XmlElement photo = doc.CreateElement("photo");

            sno.InnerText = sno_txtbx.Text;
            sname.InnerText = sname_txtbx.Text;
            course.InnerText = course_txtbx.Text;
            fee.InnerText = fee_txtbx.Text;
            string ppath = pictureBox1.ImageLocation;       
            photo.InnerText == ppath.Substring(ppath.LastIndexOf('\\') + 1);       

            root.AppendChild(sno);
            root.AppendChild(sname);
            root.AppendChild(course);
            root.AppendChild(fee);
            root.AppendChild(photo);

            doc.DocumentElement.AppendChild(root);
            doc.Save(openFileDialog1.FileName);
            MessageBox.Show("record inserted");    


ii)      DataRow drow=ds.Tables[0].NewRow();
            drow[0] = sno_txtbx.Text;
            drow[1] = sname_txtbx.Text;
            drow[2] = course_txtbx.Text;
            drow[3] = fee_txtbx.Text;

            ppath = pictureBox1.ImageLocation;
            drow[4]=ppath.Substring(ppath.LastIndexOf('\\') + 1);

            ds.Tables[0].Rows.Add(drow);
            ds.WriteXml(fpath);
            MessageBox.Show("record inserted");

Update Code:

    if (sno_txtbx.Text!= null)
            {
                DataRow drow = ds.Tables[0].Rows.Find(sno_txtbx.Text);            
                rno = ds.Tables[0].Rows.IndexOf(drow);

                ds.Tables[0].Rows[rno][0]=sno_txtbx.Text;
                ds.Tables[0].Rows[rno][1]= sname_txtbx.Text;
                ds.Tables[0].Rows[rno][2]=course_txtbx.Text;
                ds.Tables[0].Rows[rno][3]=fee_txtbx.Text;

                ppath = pictureBox1.ImageLocation;
                ds.Tables[0].Rows[rno][4] = ppath.Substring(ppath.LastIndexOf('\\') + 1);

                ds.WriteXml(openFileDialog1.FileName);
                MessageBox.Show("record updated");
            }


Delete Code:

    if (sno_txtbx.Text != null)
            {
                DataRow drow = ds.Tables[0].Rows.Find(sno_txtbx.Text);
                ds.Tables[0].Rows.Remove(drow);

                ds.WriteXml(openFileDialog1.FileName);
                MessageBox.Show("record deleted");
                rno = 0;
                showdata();


Note:
use browse button for placing photo in the picturebox

 private void browsebtn_Click(object sender, EventArgs e)
        {
            openFileDialog2.Filter = "bmp|*.bmp|jpeg|*.jpg|all files|*.*";
            DialogResult res = openFileDialog2.ShowDialog();
            if (res == DialogResult.OK)
            {
                pictureBox1.ImageLocation = openFileDialog2.FileName;
            }
        }
---------------
Thanks for Ur feedback
~ Ur's Prashanth.Chindam

Posted by Prashanth Chindam Oct 20, 2010

great code..

but can i add adding,edit,and del button..?whats the code..?thx b4

Posted by angelo sucks Oct 12, 2010
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.