Posts Tagged ‘node’

Get dataset from xml document using XmlNodeReader

February 1, 2012 1 comment

Hi, many times we need to read an xml file and get it in either dataset or datatable. This is ok till we directly use dataset.readXML method, but what when we just need to read specific nodes (infact elements) and then create dataset/datatable out-of it? (quite tricky right)

The answer is create an XmlNodeReader object and get the required element (node) into it either by traversing the xml document or by firing a simple (yet powerful) XPath Query on to the document.  The below sample explains the same by making use of Xpath Query.

private void btnGetData_Click(object sender, EventArgs e)
//Create xmlnode and xmlElement for xpath
XmlNode xmlNode;
XmlElement root = doc.DocumentElement;

// xpath expression //List[@Name=’Lotus Machines’]
xmlNode = root.SelectSingleNode(txtExpression.Text);

DataSet dataSet = new DataSet();
if (xmlNode.HasChildNodes)
for (int indexNode = 0; indexNode < xmlNode.ChildNodes[0].ChildNodes.Count; indexNode++)
XmlNode innerNode = xmlNode.ChildNodes[0].ChildNodes[indexNode];
using (XmlNodeReader reader = new XmlNodeReader(innerNode))
{// fill dataset from reader object as below 🙂

I would definitely like to hear from ur side if there is any other better way for so… till the bye bye  🙂