XML

How to XML in C#
XML is a general purpose tag based language and very easy to transfer and store data across applications. Like HTML , XML is a subset of SGML (Standard Generalized Markup Language). XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify what information it contains.
XML files are made up of tags that contains data. Generally a start tag and end tag to hold the data. For example, if you want to create an XML tag name "Header" , the start tag is like < Header > and the end tag is like < /Header > . We can fill our information between these tags.
< Header > Header Content Here < /Header >
While creating an XML file , some important points have to remember :
* XML is case sensitive
ex: < Header > is not same as < HeadeR > .
* Tags must be closed in the reverse order that they were opened
ex : < first-tag >< second-tag > Data here < /second-tag > < /first-tag >
Sample XML File
Description: product
The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . These classes are stored in the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal storage format.
You can use any text editor to create an XML file . More over XML files are readable by humans as well as computers. From the following links you can see how to use XML in C# Programming Language.

How to open and read an XML file in C#



XML is a self describing language and it gives the data as well as the rules to extract what data it contains. Reading an XML file means that we are reading the information embedded in XMLtags in an XML file.
In the previous program we create an XML file and named it as products.xml. The following C# program read that file and extract the contents inside the XML tag. We can read an XML file in several ways depends on our requirement. This program read the content in Node wise . Here we are using XmlDataDocument Class to read the XML file . In this program it search the Node and its child Nodes and extract the data in child nodes.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNodeList xmlnode ;
            int i = 0;
            string str = null;
            FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
            xmldoc.Load(fs);
            xmlnode = xmldoc.GetElementsByTagName("Product");
            for (i = 0; i <= xmlnode.Count - 1; i++)
            {
                xmlnode[i].ChildNodes.Item(0).InnerText.Trim();
                str = xmlnode[i].ChildNodes.Item(0).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(1).InnerText.Trim() + " | " + xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
                MessageBox.Show (str);
            }
        }
    }
}

How to create XML file from Dataset
XML is a tag based language, that means the document is made up of XML tags that contain information. We can create an XML file in several ways.
In the previous section we created an XML file using XmlTextWriter Class . Here we are creating an XML file Product.XML using an ADO.NET Dataset. In order to create this, we have to manually create a Datatable first and add the data of Product.XML in the Datatable . Then add the Datatable in a Dataset . Call the method WriteXml of Dataset and pass the file name Product.XML as argument.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;


namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        DataTable dt;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            dt = new DataTable();
            dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32")));
            dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32")));
            fillRows(1, "product1", 1111);
            fillRows(2, "product2", 2222);
            fillRows(3, "product3", 3333);
            fillRows(4, "product4", 4444);
            ds.Tables.Add(dt);
            ds.Tables[0].TableName = "product";
            ds.WriteXml("Product.xml");
            MessageBox .Show ("Done");
        }

        private void fillRows(int pID, string pName, int pPrice)
        {
            DataRow dr ;
            dr = dt.NewRow();
            dr["Product_ID"] = pID;
            dr["Product_Name"] = pName;
            dr["product_Price"] = pPrice;
            dt.Rows.Add(dr);
        }
    }
}
How to Open and read an XML file to Dataset
XML is a platform independent language, so the information formatted in XML can be use in any other platforms (Operating Systems) . The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .
In the previous section we already saw how to read an XML file through Node navigation . Here we are going to read an XML file using a DataSet. Here Dataset is using an XmlReader for read the content of the file. Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset.
Click here to download the input file product.xml : product.xml

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlReader xmlFile ;
            xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
            DataSet ds = new DataSet();
            ds.ReadXml(xmlFile);
            int i = 0;
            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[2].ToString());
            }
        }
    }
}
How to create an XML file from SQL
XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format.
There are several ways to create an XML file . In the previous sections we already saw how to create an XML file using XmlTextWriter and also created an XML file using manually created Dataset. Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml()method and pass the file name as argument.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection );
            SqlDataAdapter adapter ;
            DataSet ds = new DataSet();
            string sql = null;

            connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";
            connection = new SqlConnection(connetionString);
            sql = "select * from Product";
            try
            {
                connection.Open();
                adapter = new SqlDataAdapter(sql, connection);
                adapter.Fill(ds);
                connection.Close();
                ds.WriteXml("Product.xml");
                MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString());

            }
        }
    }
}
How to search in a XML file
XML files are made up of tags that contains information. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format.
The following C# source code shows how to search an item in a XML file using Dataset . Here Dataset using an XmlReader for read the content of the file. Locate the XML file usingXmlReader and pass the XmlReader as argument of Dataset. By using the Dataset , search the product Product2 in the file Product.XML with the help of DataView.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlReader xmlFile ;
            xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
            DataSet ds = new DataSet();
            DataView dv ;
            ds.ReadXml(xmlFile);

            dv = new DataView(ds.Tables[0]);
            dv.Sort = "Product_Name";
            int index = dv.Find("Product2");

            if (index == -1)
            {
                MessageBox.Show ("Item Not Found");
            }
            else
            {
                MessageBox.Show(dv[index]["Product_Name"].ToString() + " " + dv[index]["Product_Price"].ToString());

            }
        }
    }
}
How to filter in a XML file
XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). Once we create an XML file in one platform it can be used in other platforms also. The .Net technology is widely supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal storage format.
Here we are going to filter an XML file content and store the result in a newly created XML file through C#. We have an XML file Product.XML , and it has a field Product_Price. We are giving a search criteria like the Product_Price >= 3000 and store the result in a newly created XML file Result.XML .

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlReader xmlFile ;
            xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
            DataSet ds = new DataSet();
            DataView dv ;
            ds.ReadXml(xmlFile);
            dv = new DataView(ds.Tables[0], "Product_price > = 3000", "Product_Name", DataViewRowState.CurrentRows);
            dv.ToTable().WriteXml("Result.xml");
            MessageBox.Show ("Done");
        }
    }
}

You can see the filter result in Result.xml file
Click here to download the input file product.xml : product.xml
How to insert data from XML to database
XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net technology is widely supported XML file format. The .Net Frameworkprovides the Classes for read, write, and other operations in XML formatted files . Moreover the Dataset in ADO.NET uses XML format as its internal storage format.
Here we are going to insert the values of an XML file to a Database Table using SQL Insert Command . Here the Dataset using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. Also establish a connection to the Database using a connectionstring . After getting the data from XML file to the Dataset , we can loop through the dataset values and use insert command to add the values to the Product table in the Databse.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string connetionString = null;
            SqlConnection connection;
            SqlCommand command ;
            SqlDataAdapter adpter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            XmlReader xmlFile ;
            string sql = null;

            int product_ID = 0;
            string Product_Name = null;
            double product_Price = 0;

            connetionString = "Data Source=servername;Initial Catalog=databsename;User ID=username;Password=password";

            connection = new SqlConnection(connetionString);

            xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
            ds.ReadXml(xmlFile);
            int i = 0;
            connection.Open();
            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                product_ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
                Product_Name = ds.Tables[0].Rows[i].ItemArray[1].ToString();
                product_Price = Convert.ToDouble(ds.Tables[0].Rows[i].ItemArray[2]);
                sql = "insert into Product values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
                command = new SqlCommand(sql, connection);
                adpter.InsertCommand = command;
                adpter.InsertCommand.ExecuteNonQuery();
            }
            connection.Close();
            MessageBox.Show("Done .. ");
        }
    }
}

You have to pass necessary database connection information to connection string.
Click here to download the input file product.xml : product.xml

How to create Excel file from XML
XML is a platform independent language, so the information formatted in XML can be used in any other platforms (Operating Systems). XML is a self describing language and it gives the data as well as the rules to identify what the data it contains.
Here we are going to read from an XML file content and write the same content to an Excel file. Here using an XmlReader for read the XML file to the Dataset . Loop through the Dataset and add the content to the Excel file . For create an excel file you have to add reference of Excel library to you project , follow the link C# Create Excel File for details.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp ;
            Excel.Workbook xlWorkBook ;
            Excel.Worksheet xlWorkSheet ;
            object misValue = System.Reflection.Missing.Value;

            DataSet ds = new DataSet();
            XmlReader xmlFile ;
            int i = 0;
            int j = 0;

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
            ds.ReadXml(xmlFile);

            for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
                {
                    xlWorkSheet.Cells[i + 1, j + 1] = ds.Tables[0].Rows[i].ItemArray[j].ToString ();
                }
            }

            xlWorkBook.SaveAs("Specify path here\\xml2excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlApp);
            releaseObject(xlWorkBook);
            releaseObject(xlWorkSheet);

            MessageBox.Show("Done .. ");
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}

Click here to download the input file product.xml : product.xml 

How to create XML file from Excel
XML is a general purpose tag based language and very easy to transfer and store data across applications. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .
The following C# program shows how to create an XML file from an Excel file content . Here we are using an OleDbConnection to read the excel file and store the content to a Dataset . Call the method WriteXml of Dataset to write to the XML file.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                System.Data.OleDb.OleDbConnection MyConnection ;
                System.Data.DataSet ds ;
                System.Data.OleDb.OleDbDataAdapter MyCommand ;
                MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='Specify path here \\xl2xml.xls';Extended Properties=Excel 8.0;");
                MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
                MyCommand.TableMappings.Add("Table", "Product");
                ds = new System.Data.DataSet();
                MyCommand.Fill(ds);
                MyConnection.Close();
                ds.WriteXml("Product.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString());
            }
        }


    }
}

How to XML to DataGridView
XML is a platform independent language, so the information formatted in XML file can be use in any other platforms . The .Net technology is widely supported XML file format.
The following C# source code shows , how to load data in a DataGridView from an XML file . Here the Dataset using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of Dataset. When the Dataset retrieves the data, it passes as DataSource to DataGridView .

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.Data;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                XmlReader xmlFile ;
                xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
                DataSet ds = new DataSet();
                ds.ReadXml(xmlFile);
                dataGridView1.DataSource = ds.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show (ex.ToString());
            }
        }


    }
}

How to create a TreeView from XML File
XML is a self describing language and it gives the data as well as the rules to extract what the data it contains. Reading an XML file means that we are reading the data embedded in tags in an XML file.
Description: xml-tree
In the previous example we already saw how to read an XML file Node wise. Here we are reading XML file as Node and pass the Nodes data to TreeView .

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            XmlDataDocument xmldoc = new XmlDataDocument();
            XmlNode xmlnode ;
            FileStream fs = new FileStream("tree.xml", FileMode.Open, FileAccess.Read);
            xmldoc.Load(fs);
            xmlnode = xmldoc.ChildNodes[1];
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));
            TreeNode tNode ;
            tNode = treeView1.Nodes[0];
            AddNode(xmlnode, tNode);
        }

        private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
        {
            XmlNode xNode ;
            TreeNode tNode ;
            XmlNodeList nodeList ;
            int i = 0;
            if (inXmlNode.HasChildNodes)
            {
                nodeList = inXmlNode.ChildNodes;
                for (i = 0; i <= nodeList.Count - 1; i++)
                {
                    xNode = inXmlNode.ChildNodes[i];
                    inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = inTreeNode.Nodes[i];
                    AddNode(xNode, tNode);
                }
            }
            else
            {
                inTreeNode.Text = inXmlNode.InnerText.ToString();
            }
        }
    }
}

Usually we are generating Crystal Reports from Databases , here in the following section describes how to create a Crystal reports from XML file in C#. This is very similar to creating Crystal Reports from database , the only difference is that you have to select the data source as the XML file at the designing time of Crystal Report in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
In order to generating Crystal Report from XML file , we have to create an XML file . Here we are going to create an XML file and name it as Product.XML . The structure of the Product.XML file is same as the Product table in the crystaldb database earlier mentioned in this section C# crystaldb . The content of the product.xml is shown below.
Description: csharp-crystal-report-product-xml
Generating Crystal Report from XML file is very similar to generating Crystal Report from Databases. The only difference is happened when you selecting the datasource part. Here you have to select Create New Connection - Database Files and select the XML file you want to generate Crystal Reports (In this case you select the Product.xml ).
Description: csharp-crystal-report-xml-select
Select all the fields from Product and click finish button
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
Copy and paste the following source code and run your C# project

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
            crystalReportViewer1.ReportSource = cryRpt;
            crystalReportViewer1.Refresh();
        }
    }
}

NOTES: 
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt"); 

The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal Reports file like c:\projects\crystalreports\CrystalReport1.rpt

XML Serialization
Serialization of XML to Common Language Runtime Objects enables one to convert XML documents into a form where they are easier to process using conventional programming languages. The .Net technology is widely supported XML file format. The .Net Framework provides the Classes for read, write, and other operations in XML formatted files .
The following C# program shows how to serialize a Dataset to an XML disk file . Here we are using XmlSerializer Class for serialize the Dataset Object.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml.Serialization ;
using System.IO;


namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        DataTable dt;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            dt = new DataTable();
            dt.Columns.Add(new DataColumn("Product_ID", Type.GetType("System.Int32")));
            dt.Columns.Add(new DataColumn("Product_Name", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("product_Price", Type.GetType("System.Int32")));
            fillRows(1, "product1", 9999);
            fillRows(2, "product2", 2222);
            fillRows(3, "product3", 3333);
            fillRows(4, "product4", 4444);
            ds.Tables.Add(dt);
            ds.Tables[0].TableName = "product";

            StreamWriter serialWriter ;
            serialWriter = new StreamWriter("serialXML.xml");
            XmlSerializer xmlWriter = new XmlSerializer(ds.GetType());
            xmlWriter.Serialize(serialWriter, ds);
            serialWriter.Close();
            ds.Clear();
        }

        private void fillRows(int pID, string pName, int pPrice)
        {
            DataRow dr ;
            dr = dt.NewRow();
            dr["Product_ID"] = pID;
            dr["Product_Name"] = pName;
            dr["product_Price"] = pPrice;
            dt.Rows.Add(dr);
        }
   }
}

Click here to download serialXML.xml 
XML DeSerialization
XML is a general purpose tag based language and very easy to transfer and store data across applications. XML Serialization is the process of serializing a .Net Object to the form of XML file or from an XML to .Net Object.
During XML serialization, only the public properties and fields of an object are serialized. The following C# source code shows how to De-Serialize the DataSet as it is streamed from an XML file back into memory.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml.Serialization ;
using System.IO;


namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
            FileStream readStream = new FileStream("serialXML.xml", FileMode.Open);
            ds = (DataSet)xmlSerializer.Deserialize(readStream);
            readStream.Close();
            dataGridView1.DataSource = ds.Tables[0];
        }


   }
}

Click here to download serialXML.xml 

No comments:

Post a Comment