How to Convert Xmlnode to Dataset

Save

An XMLNode and DataSet are two ASP.NET components used to transfer data from an XML data string to a DataSet that displays the information to your Web page readers. You must create the DataSet in your ASP.NET function, and then transfer the node list to the DataSet using serialization methods. For instance, bind the DataSet to a DataGrid to display the rows and columns programmatically in the Web page.

  • Open the ASP.NET code file you want to use to create the DataSet and transfer the XML node list. In the beginning of the code function, add the following code to get the XML file node list you want to use:
    XmlDocument doc = new XmlDocument();

        doc.Load(Server.MapPath("contacts.xml"));
    XmlElement root = doc.DocumentElement;

    XmlNodeList list = root.GetElementsByTagName("Category");
    In this example, the "contacts.xml" file opens, and a list of elements are contained in the "list" variable.

  • Create the DataSet columns you want to use for the XMLNode list. Each column contains a field from the node list. The following code loops through each node list from the "list" variable and assigns a column and a column header to the table:
    DataTable dt = new DataTable();

        int colcount= 0;
    foreach (XmlNode node in list.Item(0).ChildNodes)
    {
    colcount++;

    DataColumn dc = new DataColumn(node.Name, System.Type.GetType("System.String"));
    dt.Columns.Add(dc);
    }

  • Add the rows to the DataSet. The DataSet rows represent the records from the XMLNode list. Add the following code:
    for (int i = 0; i < list.Count; i++)

        {
    DataRow dr = dt.NewRow();
    for (int j = 0; j &lt; colcount; j++)
    {
    dr[j] = list.Item(i).ChildNodes[j].InnerText;
    }
    dt.Rows.Add(dr);
    }
  • Bind the new DataSet to a GridView. A GridView is an ASP.NET component used to translate the data from a DataSet to an object on the Web page. It displays the data in a way that makes it easy to read for the website customers. Add the following code:
    GridView1.DataSource = dt;

        GridView1.DataBind();

References

  • Photo Credit Jason Reed/Photodisc/Getty Images
Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!