Friday, September 3, 2010

Parse XML and store to DataTable

Parse the xml results and store data to Datatable.Below a Method will Display Data in Lables using result DataTable when URL is passed.

public void DisplaySearchResults(string URL)
{
XmlDocument myXMLDocument = null;
DataRow drDetails;
string ID;
string Title;
string Desc;
Label lblErrorMessage= new Label();

DataTable dtSearchResults = new DataTable();
try
{
myXMLDocument = new XmlDocument();
myXMLDocument.Load(URL);
XmlNodeList objNodeList = myXMLDocument.SelectNodes("Root/Child1/);
DataColumn dcID = new DataColumn("ID", typeof(string));
DataColumn dcTitle = new DataColumn("Title", typeof(string));
DataColumn dcDesc= new DataColumn("Description", typeof(string));
dtSearchResults.Columns.Add(dcID);
dtSearchResults.Columns.Add(dcTitle);
dtSearchResults.Columns.Add(dcDesc);
foreach (XmlNode hitNode in objNodeList)
{

drDetails = dtSearchResults.NewRow();
ID = hitNode.SelectSingleNode("FIELD[@NAME='id']").InnerText;
drDetails["ID"] = ID;


Title = hitNode.SelectSingleNode("FIELD[@NAME='title']").InnerText;
drDetails["Title"] = Title;

Desc = hitNode.SelectSingleNode("FIELD[@NAME='desc']").InnerText;
drDetails["Description"] = Desc;

dtSearchResults.Rows.Add(drDetails);
dtSearchResults.AcceptChanges();

}

TableRow row;
TableCell cell1;
TableRow rowbody;
TableCell cell2;
Label lblTitle;
Label lblbodytext;

lblErrorMessage.Text = "";
if (dtSearchResults.Rows.Count > 0)
{
for (int i = 0; i < dtSearchResults.Rows.Count; i++)
{
row = new TableRow();
rowbody = new TableRow();
cell1 = new TableCell();
cell2 = new TableCell();

lblTitle = new Label();

lblTitle.Text = dtSearchResults.Rows[i]["Title"].ToString();
cell1.Controls.Add(lblTitle);
lblbodytext = new Label();
lblbodytext.Text = dtSearchResults.Rows[i]["Description"].ToString();

cell2.Controls.Add(lblbodytext);
row.Cells.Add(cell1);
rowbody.Cells.Add(cell2);
tblsearchresults.Rows.Add(row);
tblsearchresults.Rows.Add(rowbody);

}
}
else
{
lblErrorMessage.Text = "No search results were found. Please try again";

}

Define a asp table in your ASPX page like below


This is basic solution, you can also do paging of xml result set like Google or Bing.

If this solution helped anyone Please leave a comment.

Enjoy Coding :)

No comments: