Saturday, July 24, 2010

Xml Creation and Reading that to DataSet

 Creating XML and Reading that is  very important when we come to Web-service, Serialization etc
Here i just give the basics of  creating and reading xml.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

//Creating Xml Node..........................

            XmlDocument Xdoc = new XmlDocument();
            XmlElement Xelm1 = Xdoc.CreateElement("MainNode");
            Xdoc.AppendChild(Xelm1);


            //Appending text node to the subnode........

                XmlElement Xelm2 = Xdoc.CreateElement("Number");
                XmlText xmlText = Xdoc.CreateTextNode("data");
                Xelm2.AppendChild(xmlText);


            //Appending SubNode to Main Node....
                Xelm1.AppendChild(Xelm2);
           
              
         //Writing Xml ........................
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);
            xw.Formatting = Formatting.Indented;
            Xdoc.WriteTo(xw);
            string xmlstr =""+ sw.ToString()+"";

            //Loading Data to DataSet From XML................

            DataSet ds = new DataSet();
            foreach (DataTable dt in ds.Tables)
                dt.BeginLoadData();
            ds.ReadXml(new StringReader(xmlstr));
           foreach (DataTable dt in ds.Tables)
                dt.EndLoadData();

            //Setting Datasource to datagridview..................

            dataGridView1.DataSource = ds.Tables["MainNode"];

No comments:

Post a Comment