EziData Solutions

Web, NET and SQL Server

Filtering XML data in a DataSet

In the post Read XML File into DataSet we demonstrated how to read every row of data from an XML document by using the ReadXml method. While reading every row of data may be suitable for a smalll set of data, there are few times when you will actually want to return every record from the XML document. There are a number of ways to filter data from an XML document, such as using XQuery which filters the data at the XML Document level. In this example however we will conduct the filtering at the DataSet level, once it has been populated from the XML Document. 

To filter out only the records we want from the DataSet, we will use the DataTable.Select method, as outlined below.

        //declare and load the DataSet from the XML document

        DataSet ds = new DataSet();

        ds.ReadXml("AppSettings.xml");

 

        //only select the rows where the name is CurrentInstance

        DataRow[] rows = ds.Tables[0].Select("name='CurrentInstance'");

 

        //Loop thru the rows to access each row that matches

        foreach (DataRow row in rows)

        {

            //TODO: do something with each row

        }

As you can see the DataTable.Select method returns an array of DataRow objects. We are using the constructor that takes a filterExpression as an argument. In this example we are using a simple equality filterExpression - return all records where name is equal to CurrentInstance. Depending on the datatype of the columns in your DataTable you could create a valid expression using any common operators such as Like, > (greater than), < (less than) and even join multiple exressions together using AND/OR.

Posted: Oct 27 2010, 23:11 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: C# | XML