8.7. Transforming a DataSet Using XSLT

Problem

You need to use an XSLT stylesheet to transform the contents of a DataSet.

Solution

Create an XslTransform object and call the Transform( ) method.

You’ll need to add the Microsoft Web Browser control to the Toolbox from the COM tab in the Customize Toolbox Dialog. You’ll also need a reference to the Microsoft HTML Object Library from the COM tab in Visual Studio .NET’s Add Reference Dialog.

Example 8-10 uses one XML file:

Category.xslt

The XSLT stylesheet used to transform the XML for the Categories table in the DataSet into HTML displaying the Categories data in an HTML table. The contents of this XML file are shown in Example 8-10.

The sample code contains three event handlers:

Form.Load

Sets up the sample by filling a DataSet with the Categories table from Northwind.

Transform Button.Click

Initializes a WebBrowser control. Once the control is initialized, the DocumentComplete event is raised. The handler for the DocumentComplete event completes the XSLT transformation.

DocumentComplete

Gets the XmlDataDocument for the DataSet, creates an XSLTransform class, and transforms the XML document using the XSLT stylesheet. The results are displayed both in the WebBrowser control and as XML.

Example 8-10. File: Category.xslt

<?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet xmlns:xsl=http://www.w3.org/1999/XSL/Transform version="1.0"> <xsl:template match="/"> <html> <body> <table> <tr bgcolor="#AAAAAA"> <td>Category ID</td> <td>Name</td> <td>Description</td> ...

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.