Thursday, 29 March 2012

How to working with xml in .net?


XmlDocument and XmlDataDocument are a classes which is used to work with xml doucments in the form of memory objects.
XmlDocument:
xmlDocument is an in-memory object which loads the entire document into memory then perform the requried operations.

How to Load an xml file to XmlDocument Class?
XmlDocument loads the xml file as a in-memory.to load the xml file to in memory this object has 2 ways
1.  Load(string filename)
2.  LoadXml(“<book><id>1</id></book>”);
Class Declaration:
XmlDocument xmldoc;      XmlNode n;
Under Load Button
xmldoc = new XmlDocument();
            xmldoc.Load(textBox1.Text);
         
Then xmlDocument load the data. As in MEMORY.
Then Find the data.now data is available as IN-MEMORY.
Then we have 2 methods to pointing a particular elements in the xml document using xpath so we have 2 methods like
SingleNodes
SelectSinglNode accepts xpath query to retrive particular data to memory.
Like
private void Find(object sender, EventArgs e)
{         
           n = xmldoc.SelectSingleNode(@"/NewDataSet/jobs[job_id="+Convert.ToInt32(textBox6.Text)+"]");                       
            if(n!=null)
            {                  
                    textBox2.Text=n.ChildNodes[0].InnerText;
                    textBox3.Text=n.ChildNodes[1].InnerText;
                    textBox4.Text=n.ChildNodes[2].InnerText;
                    textBox5.Text=n.ChildNodes[3].InnerText;
            }
            else
                MessageBox.Show("absent today");
        }
Now here n pointing particular data.
How to retrive data of a particular Element ?
Under GetNames
private void GetNames(object sender, EventArgs e)
{
            listBox1.Items.Clear();
             XmlNodeList nl=xmldoc.GetElementsByTagName("job_desc");
           
                foreach (XmlNode n in nl)
                {
                    listBox1.Items.Add(n.InnerText);
                   
                }  
}
How to   save   the data after modifications in xml file(document)?
private void save(object sender, EventArgs e)
        {// after n is find, then n----->pointing to a node save modification of THAT** childnods is possible.
            n.ChildNodes[1].InnerText = textBox3.Text;
            n.ChildNodes[2].InnerText = textBox4.Text;
            n.ChildNodes[3].InnerText = textBox5.Text;
            MessageBox.Show("Data Modified");
          xmldoc.Save(textBox1.Text);
            GetNames(sender, e);
        }
How to Delete the data from the xml document?
private void Delete(object sender, EventArgs e)
{
          xmldoc.DocumentElement.RemoveChild(n);            
            xmldoc.Save(textBox1.Text);
            GetNames(sender, e);
}

No comments:

Post a Comment