Net-informations.com
SiteMap  | About    

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




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

            }
        }
    }
}

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






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.