1

My xml


<?xml version="1.0" encoding="utf-8" ?>
<Category>
  <Youth>

  </Youth>
  <GeneralStores>

  </GeneralStores>
  <Schools>

  </Schools>
  <Colleges>

  </Colleges>
  <GovernmentOffices>

  </GovernmentOffices>
  <Restaurants>

  </Restaurants>
  <MovieTheatres>

  </MovieTheatres>

</Category>

I need data table like

_______________________

Category
__________
Youth
GeneralStores
Schools
Colleges
GovernmentOffices
Restaurants
MovieTheatres

I am binding this datatable to telrik rad grid on need datasource event

here is my .cs code

protected void CategoriesRadGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
    try
    {
        //create the DataTable that will hold the data
        DataTable CategoryDT = new DataTable("MainCategory");
        CategoryDT.Columns.Add("Category", System.Type.GetType("System.String"));
      CategoryDT.ReadXml(@"C:\Users\MyID\Documents\Visual Studio 2010\Projects\SomeName\InfoXML\XMLCategory.xml");
    }
    catch (Exception ex)
    {

    }
}
  1. Code executes good with no data in data table.
  2. Also tell me How to give file location when file is on servers? presently I am using my local machine path where the file is located.
2

2 Answers 2

2

use XmlDocument to read your XML

XmlDocument doc= new XmlDocument();
doc.Load("physical path to file.xml");
// doc.LoadXml(stringXml);

DataTable dt = new DataTable();

if(doc.ChildNodes[1]!=null)
   dt.Columns.Add(doc.ChildNodes[1].Name); //Assuming you want the rood node to be the only column of the datatable

 //iterate through all the childnodes of your root i.e. Category
foreach(XmlNode node in doc.ChildNodes [1].ChildNodes )
{
  dt.Rows.Add(node.Name);
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Try the following:

private static DataTable BuildDataTable(XElement x)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add(new DataColumn(x.Name.ToString()));
            foreach (var d in x.Descendants())
            {
                DataRow drow = dt.NewRow();
                drow[0] = d.Value;
                dt.Rows.Add(drow);
            }

            return dt;
        }

the method will iterate through the xml and create the dataTable. Xelement is part linq and will require .Net framework 4. It represents an XML element.

To call the method :

//this answers your second question, 
//use Server.MapPath to find your file.
XElement x = XElement.Load(Server.MapPath(".") + @"\test.xml");

DataTable dt = BuildDataTable(x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.