Home > General > Get dataset from xml document using XmlNodeReader

Get dataset from xml document using XmlNodeReader


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 🙂
dataSet.ReadXml(reader);
}
}
}
}

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

Advertisements
  1. Bhabesh
    January 8, 2013 at 6:15 am

    Data at the root level is invalid. Line 1, position 1.
    Getting this error

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: