Monday, October 11, 2010

BENEFITS OF XMLDATADOCUMENT OVER XMLDOCUMENT

Recently I came across a requirement, where I need to fetch the data from GridView and convert it to XML.
I had a predefined format of XML, in which I need to save the data :
<root>
<rec>
<amount />
<remark />
</rec>
<rec>
<amount />
<remark />
</rec>
</root>
Also, I have a checkbox in the first column of GridView. I have to fetch records for which checkbox is checked.

I can use either XMLDocument or XMLDataDocument for the same.

1. Using XMLDocument:XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("root"); xmlDoc.AppendChild(root);
foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
XmlElement rec = xmlDoc.CreateElement("rec");
root.AppendChild(rec);
XmlElement topupid = xmlDoc.CreateElement("topupid");
topupid.InnerText = grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString();
rec.AppendChild(topupid);
XmlElement amount = xmlDoc.CreateElement("amount");
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
amount.InnerText = txtAmount.Text.Trim();
rec.AppendChild(amount);
XmlElement remarks = xmlDoc.CreateElement("remarks");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
remarks.InnerText = txtRemarks.Text.Trim();
rec.AppendChild(remarks);
}
}
2. Using XMLDataDocument :

DataSet dataSet = new DataSet("root");
DataTable dataTable = new DataTable("rec");
dataTable.Columns.AddRange(new DataColumn[]
{
new DataColumn("topupid"),
new DataColumn("amount"),
new DataColumn("remarks")
});

foreach (GridViewRow Row in grdTest.Rows)
{
CheckBox chkTopUpRequest = (CheckBox)Row.FindControl("chkRequest");
if (null != chkTopUpRequest && chkTopUpRequest.Checked)
{
TextBox txtAmount = (TextBox)Row.FindControl("txtAmount");
TextBox txtRemarks = (TextBox)Row.FindControl("txtRemarks");
dataTable.Rows.Add(grdTopUpRequest.DataKeys[Row.RowIndex].Value.ToString(),
txtAmount.Text.Trim(),
txtRemarks.Text.Trim());
}
}
dataSet.Tables.Add(dataTable);
XmlDataDocument xmlDataDoc = new XmlDataDocument(dataSet);


XMLDocument is an in-memory (cache) tree representation of an XML document and enables the navigation and editing of this document.

The XmlDataDocument class extends XmlDocument and allows structured data to be stored, retrieved, and manipulated through a relational DataSet. This class allows components to mix XML and relational views of the underlying data.


Bookmark and Share

No comments:

Post a Comment