Monday, February 6, 2012

Search in XML file using ASP.Net

Search element in XML file using
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 .

<Product_name>Product 1</Product_name>

<Product_name>Product 2</Product_name>

<Product_name>Product 3</Product_name>

<Product_name>Product 4</Product_name>

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 ;

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

            if (index == -1)
               Response.write("Item Not Found");
            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.

No comments:

Post a Comment