Apr 24, 2012

How Read XML file in C#


This article will guide you how to display XML content in Gridview

XMLFile content
<ProductList>
    <Products>
        <ProductId>1</ProductId>
        <ProductName>Aniseed Syrup</ProductName>
        <UnitPrice>27</UnitPrice>
    </Products>
    <Products>
        <ProductId>2</ProductId>
        <ProductName>Chef Anton's Cajun Seasoning</ProductName>
        <UnitPrice>20</UnitPrice>
    </Products>
    <Products>
        <ProductId>3</ProductId>
        <ProductName>Queso Cabrales</ProductName>
        <UnitPrice>28</UnitPrice>
    </Products>
    <Products>
        <ProductId>4</ProductId>
        <ProductName>Alice Mutton</ProductName>
        <UnitPrice>24</UnitPrice>
    </Products>
    <Products>
        <ProductId>5</ProductId>
        <ProductName>Sasquatch Ale</ProductName>
        <UnitPrice>30</UnitPrice>
    </Products>
</ProductList>

In Web Forms



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath("Products.xml"));
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }      
    }
}

In Windows Forms




using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Read_XML_file_Windows_Forms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DataSet ds = new DataSet();
            ds.ReadXml("C:\\Products.xml");
            dataGridView1.DataSource = ds.Tables[0];
        }
    }
}



No comments:

Post a Comment