Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

Thursday, 29 March 2012

How to Prepare Document programatically ?


XmlDocument/XmlDataDocument objects contains CreateElement and CreateAttribute methods that are used to add nodes to the XmlDocument object.
XmlElement Contains a property Attributes Property which is an XmlAttributeCollection . this is inhirets from XmlNamedNodeMap class
Demo:
Prepare xml document programmatic:
           XmlDocument xmldoc = new XmlDocument();
           xmldoc.AppendChild(xmldoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
           XmlElement x=xmldoc.CreateElement("Root");
           
           XmlElement newjob = xmldoc.CreateElement("jobs"); // parent
           XmlElement jobid = xmldoc.CreateElement("job_ids");
           jobid.InnerText = txtJobid.Text;           
           XmlElement jobname = xmldoc.CreateElement("job_desc");
           jobname.InnerText = txtJobdesc.Text;
           XmlElement minsal = xmldoc.CreateElement("min_lvl");
           minsal.InnerText = txtminlvl.Text;
           XmlElement maxsal = xmldoc.CreateElement("max_lvl");
           maxsal.InnerText = txtmaxlvl.Text;
           newjob.AppendChild(jobid);
           newjob.AppendChild(jobname);
           newjob.AppendChild(minsal);
           newjob.AppendChild(maxsal);
           x.AppendChild(newjob);
           xmldoc.AppendChild(x);   // End the Root.                                          
           xmldoc.Save("C:\\jobs12345.xml");     // the the xml file to disk
           Label1.Text = "create xml document programmatically...";
How to add Attributes to xmlElements?
For adding Attributes to XmlElement we have a class is XmlAttribute class.
Ex:
Prepare xml document programmatic along with Attributes:
XmlDocument myDoc = new XmlDocument();
myDoc.AppendChild(myDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
            //The Father
            XmlElement Father = myDoc.CreateElement("Father");
            //Create attributes
            XmlAttribute FatherName = myDoc.CreateAttribute("Name");
            XmlAttribute FatherAge = myDoc.CreateAttribute("Age");
            //Add values to attributes
            FatherName.Value = "My father";
            FatherAge.Value = "65";
            //Append attributes to their correspondent element
            Father.Attributes.Append(FatherName);
            Father.Attributes.Append(FatherAge);
            //Add the element to the Familie node
            Familie.AppendChild(Father);
            //The mother
            XmlElement Mother = myDoc.CreateElement("Mother");
            //Create attributes
            XmlAttribute MotherName = myDoc.CreateAttribute("Name");
            XmlAttribute MotherAge = myDoc.CreateAttribute("Age");
            //Add values to attributes
            MotherName.Value = "My mother";
            MotherAge.Value = "60";
            //Append attributes to their correspondent element
            Mother.Attributes.Append(MotherName);
            Mother.Attributes.Append(MotherAge);
            //Add the element to the Familie node
            Familie.AppendChild(Mother);
            //The sister
            XmlElement Sister = myDoc.CreateElement("Sister");
            //Create attributes
            XmlAttribute SisterName = myDoc.CreateAttribute("Name");
            XmlAttribute SisterAge = myDoc.CreateAttribute("Age");
            //Add values to attributes
            SisterName.Value = "My sister";
            SisterAge.Value = "20";
            //Append attributes to their correspondent element
            Sister.Attributes.Append(SisterName);
            Sister.Attributes.Append(SisterAge);
            //Add the element to the Familie node
            Familie.AppendChild(Sister);
            //The brother
            XmlElement Brother = myDoc.CreateElement("Brother");
            //Create attributes
            XmlAttribute BrotherName = myDoc.CreateAttribute("Name");
            XmlAttribute BrotherAge = myDoc.CreateAttribute("Age");
            //Add values to attributes
            BrotherName.Value = "My brother";
            BrotherAge.Value = "21";
            //Append attributes to their correspondent element
            Brother.Attributes.Append(BrotherName);
            Brother.Attributes.Append(BrotherAge);
            //Add the element to the Familie node
            Familie.AppendChild(Brother);
            //wrapp all elements nodes in wrapper node
myDoc.AppendChild(Familie);               myDoc.Save(@"C:\myFamilssie.xml");            Console.WriteLine("Document is generated successfully!!");

Note: Don’t write XmlAttributes for declaration of xml document .to specify declaration we have
XmlDocument myDoc = new XmlDocument();
myDoc.AppendChild(myDoc.CreateXmlDeclaration("1.0", "utf-8", "yes"));
****

How to Add new Elements to Existing Xml Documents?


    How to add new Element to existing xml document?

           XmlDocument xmldoc = new XmlDocument();
           xmldoc.Load("C:\\jobs.xml");   // Loading xml file to memory
          
           XmlElement newjob = xmldoc.CreateElement("jobs"); // parent
           XmlElement jobid = xmldoc.CreateElement("job_ids");
           jobid.InnerText = txtJobid.Text;
           XmlElement jobname = xmldoc.CreateElement("job_desc");
           jobname.InnerText = txtJobdesc.Text;
           XmlElement minsal = xmldoc.CreateElement("min_lvl");
           minsal.InnerText = txtminlvl.Text;
           XmlElement maxsal = xmldoc.CreateElement("max_lvl");
           maxsal.InnerText = txtmaxlvl.Text;
           newjob.AppendChild(jobid);
           newjob.AppendChild(jobname);
           newjob.AppendChild(minsal);
           newjob.AppendChild(maxsal);
           xmldoc.DocumentElement.AppendChild(newjob);
           Label1.Text = "dadasdlfkjaskld";
           xmldoc.Save("C:\\jobs.xml");     // the the xml file to disk
            

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);
}

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...";