Showing posts with label ASP.Net with XML. Show all posts
Showing posts with label ASP.Net with XML. Show all posts

Monday, February 6, 2012

Insert data into Database from XML file


Data insertion into sqlserver2005 database from XML file using ASP.Net ,C#

This program is for to insert data into database from XML file. Here I have used sqlserver2005 to insert data. Configure the connection part according to your database name and tablename.
1)Create the Product.xml file by following coding.
2)Put the C# code within any event of an ASP.Net page.
<Table>
<Product>
<Product_id>1</Product_id>
<Product_name>Product 1</Product_name>
<Product_price>1000</Product_price>
</Product>
<Product>
<Product_id>2</Product_id>
<Product_name>Product 2</Product_name>
<Product_price>2000</Product_price>
</Product>
<Product>
<Product_id>3</Product_id>
<Product_name>Product 3</Product_name>
<Product_price>3000</Product_price>
</Product>
</Table>

insert the namespaces in your ASP.Net file


using System.Xml;
using System.Data.SqlClient;
 

Put the below code within button’s onClick event of an ASP.Net page
             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=(yourservername);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 (tablename) values(" + product_ID + ",'" + Product_Name + "'," + product_Price + ")";
                command = new SqlCommand(sql, connection);
                adpter.InsertCommand = command;
                adpter.InsertCommand.ExecuteNonQuery();
            }
            connection.Close();
         Response.write ("Data Saved");

It will save the Product.xml content into database.Don't forget to create database table according to data type of the Product.xml file. 

Search in XML file using ASP.Net


Search element in XML file using ASP.net
XML file content only tags, and .Net support widely XML .Also the Dataset in ADO.NET uses XML format as its internal storage format.
The following ASP.NETusing  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 using XmlReader 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.

The content of Product table .

<Table>
<Product>
<Product_id>1</Product_id>
<Product_name>Product 1</Product_name>
<Product_price>1000</Product_price>
</Product>

<Product>
<Product_id>2</Product_id>
<Product_name>Product 2</Product_name>
<Product_price>2000</Product_price>
</Product>

<Product>
<Product_id>3</Product_id>
<Product_name>Product 3</Product_name>
<Product_price>3000</Product_price>
</Product>

<Product>
<Product_id>4</Product_id>
<Product_name>Product 4</Product_name>
<Product_price>4000</Product_price>
</Product>
</Table>

insert the namespaces in your ASP.Net file


using System.Xml;
 
Put the below source code within button’s onclick event of a ASP.NET page

            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)
            {
               Response.write("Item Not Found");
            }
            else
            {
            Response.write(dv[index]["Product_Name"].ToString() + " " + dv[index] ["Product_Price"].ToString());

            }


It will show the product name,product index and product price from the Product.xml file.Don't forget to keep Product.xml file in same location of ASP.Net page.

Parsing XML file using ASP.NET


Parsing XML file using ASP.Net
This program will parse the XML file and it will show the content of XML file as output.

insert the namespaces in your ASP.Net file

using System.Xml;
using System.Data.SqlClient;
 
 
 
StringBuilder output = new StringBuilder();
String xmlString =
        @"<?xml version='1.0'?>
        <!-- This is a sample XML document -->
        <Items>
          <Item>test with a child element <more/> stuff</Item>
        </Items>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
    XmlWriterSettings ws = new XmlWriterSettings();
    ws.Indent = true;
    using (XmlWriter writer = XmlWriter.Create(output, ws))
    {
        // Parse the file and display each of the nodes.
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    writer.WriteStartElement(reader.Name);
                    break;
                case XmlNodeType.Text:
                    writer.WriteString(reader.Value);
                    break;
                case XmlNodeType.XmlDeclaration:
                case XmlNodeType.ProcessingInstruction:
                    writer.WriteProcessingInstruction(reader.Name, reader.Value);
                    break;
                case XmlNodeType.Comment:
                    writer.WriteComment(reader.Value);
                    break;
                case XmlNodeType.EndElement:
                    writer.WriteFullEndElement();
                    break;
            }
        }
 
    }
}
OutputTextBlock.Text = output.ToString();
 
while (reader.Read()) 
{
    switch (reader.NodeType) 
    {
        case XmlNodeType.Element: // The node is an element.
Response.write ("<" + reader.Name);
Response.write (">");
            break;
  case XmlNodeType.Text: //Display the text in each element.
Response.write (reader.Value);
            break;
  case XmlNodeType. EndElement: //Display the end of the element.
Response.write ("</" + reader.Name);
Response.write ">");
            break;
    }
}


Generating XML file in ASP.Net


Create XML file from database

The code will generate XML file in your local drive by fetching data from your sqlserver database. Just edit your connection scting and put the below code within any event of ASP.Net page.

insert the namespaces

using System.Xml;
using System.Data.SqlClient;

public partial class loadxml : System.Web.UI.Page
{

SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
         string query;

        SqlDataReader rd;
        cmd.CommandText = "select * from loginfo";
        rd = cmd.ExecuteReader();


        XmlDocument writer = new XmlDocument();
        XmlNode declaration =    writer.CreateNode(XmlNodeType.XmlDeclaration, null, null);
        writer.AppendChild(declaration);

        XmlElement root = writer.CreateElement("person");
        writer.AppendChild(root);

        while (rd.Read())
        {
string user = rd.GetSqlValue(0).ToString();
          string pass = rd.GetSqlValue(1).ToString();
          string id =  rd.GetSqlValue(2).ToString();
           
            XmlElement person1 = writer.CreateElement(id);
            root.AppendChild(person1);

            XmlElement name = writer.CreateElement("name");
            name.InnerText = user;
            person1.AppendChild(name);


            XmlElement surname = writer.CreateElement("surname");
            person1.AppendChild(surname);
            surname.InnerText = pass;
           
        }
        rd.Close();
        con.Close();

       writer.Save("D:\\sourav.xml");
}

Output:-
<person>
<user>sourav</user>
<pass>kayal</pass>
<id>1</id>
</person>



ASP.net with XML



Basic of XML
The acronym XML stands for extensible markup language. It is called extendible because you can extend it according to your wish. There is no pre define tag in XML. You can generate your won tag to describe and represent data. XML is very much user friendly and easy to parse using many programming languages(C#,PHP,JSP,JavaScript etc can able to parse XML easily). XML is w3c recommended. Generally it is  used for transfer data.
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 >
A simple example of XML file
<person>
  <name>sourav</name>
<surname>kayal</kayal>
<course>MCA</course>
</person>

Some points about XML
  •        XML is self descript language
  •         XML is case sensitive
  •         XML is truly platform independent
  •         Most of the programming language can parse XML data
  •         XML is used for represent and transfer data
  •         XML can able to parse like a tree
  •         There is one and only one root element in XML
Example of XML tree is
dom-full.gif

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.