Thursday, 29 March 2012

How ways we can work with xml documents?


In .net we can work with xml files(documents) in 2 ways.
1.       Stream Model
2.       DOM Model(Documents Object model)
Stream Model:
In order to work with stream model we have to import a namespace
using System.Xml;
XmlReader,xmlWrtier are base classes to with xml files.and perform the the basic operations also.
Base Classes

XmlReader----xmlTextReader
XmlWriter----xmlTextWriter are derived classes.to read and write xml documents.

How to Read an xml file in .net?

using System.Xml;

we have an xml file in our drive as a physically like c:\\jobs.xml

Now I want to read that xml file so we have to use object of xmlTextReader.

EX:


Under ButtonClick:

XmlReader/XmlTextReader xtr = new XmlTextReader("C:\\jobs.xml");
while(xtr.Read())
{
if (xtr.NodeType == XmlNodeType.Element && xtr.Name == "job_desc")
{
xtr.Read();
ListBox1.Items.Add(xtr.Value.ToString());
}
}
How to Write an xml doucment to Physically?
Take Controls: TextBox1,TextBox2,CheckBox1,Button1 controls
Under the ButtonClick
XmlWriter/XmlTextWriter xmlw= new XmlTextWriter(@"c:\status.xml", null);
            xmlw.WriteStartDocument();
            xmlw.WriteStartElement("Roots");
            xmlw.WriteStartElement("tasks");
            xmlw.WriteElementString("programmid", TextBox1.Text);
            xmlw.WriteElementString("task", TextBox2.Text);
   if (CheckBox1.Checked)
   {
                xmlw.WriteElementString("status", "completed");
   }
  else
   xmlw.WriteElementString("status", "incompleted");
        //    xmlw.WriteEndElement();
//  buffer is fill automatically data moves to physical file             
         
  xmlw.WriteEndElement();
  xmlw.Flush();
  xmlw.Close();           
  Label1.Text = "Data is saved Succefully...";

No comments:

Post a Comment