8.6. Using XPath to Query Data in a DataSet
Problem
You need to use an XPath expression
to extract certain rows from a DataSet
.
Solution
Use SelectSingleNode( )
or SelectNodes( )
.
The sample code contains two event handlers:
Form.Load
Sets up the sample by creating a
DataSet
containing the Orders table and Order Details table from Northwind and a nested relation between the two tables.- Go
Button.Click
Executes an XPath query to retrieve the Orders and Order Details data for an OrderID specified by the user to an
XmlNode
. The results are displayed by iterating over theXmlNode
to retrieve the Orders and theXmlNodeList
containing the Order Details.
The C# code is shown in Example 8-9.
Example 8-9. File: XPathQueryForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Text; using System.Xml; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; private const String ORDERDETAILS_TABLE = "OrderDetails"; // Relation name constants private const String ORDERS_ORDERDETAILS_RELATION = "Orders_OrderDetails_Relation"; // Field name constants private const String ORDERID_FIELD = "OrderID"; private DataSet ds; // . . . private void XPathQueryForm_Load(object sender, System.EventArgs e) { ds = new DataSet("Orders_OrderDetails"); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.