19.10. (Optional) XSLT with Class XslCompiledTransformRecall from Section 19.7 that XSLT elements define rules for converting one type of XML document to another type of XML document. We showed how to transform XML documents into XHTML documents and displayed these in Internet Explorer. The XSLT processor included in Internet Explorer (i.e., MSXML) performed the transformations. Performing an XSL Transformation in Visual Basic Using the .NET FrameworkFigure 19.30 applies the style sheet sports.xsl (Fig. 19.17) to sports.xml (Fig. 19.26) programmatically. The result of the transformation is written to an XHTML file on disk and displayed in a text box. Figure 19.30(c) shows the resulting XHTML document (sports.html) when you view it in Internet Explorer. Figure 19.30. XSLT style sheet applied to an XML document. (Part 1 of 2.)
Line 5 imports for the System.Xml.Xsl namespace, which contains class XslCompiledTransform for applying XSLT style sheets to XML documents. Line 7 declares XslCompiledTransform reference TRansformer. An object of this type serves as an XSLT processor (like MSXML in earlier examples) to transform XML data from one format to another. In event handler FrmTransformTest_Load (lines 1014), line 12 creates a new XslCompiledTransform object. Then line 13 calls the XslCompiledTransform object's Load method, which parses and loads the style sheet that this application uses. This method takes an argument specifying the name and location of the style sheetsports.xsl (Fig. 19.17) located in the current directory. Event handler btnTransform_Click (lines 1724) calls method TRansform of class XslCompiledTransform to apply the style sheet (sports.xsl) to sports.xml (line 20). This method takes two String argumentsthe first specifies the XML file to which the style sheet should be applied, and the second specifies the file in which the result of the transformation should be stored on disk. Thus the TRansform method call in line 20 transforms sports.xml to XHTML and writes the result to disk as the file sports.html. Figure 19.30(c) shows the new XHTML document rendered in Internet Explorer. Note that the output is identical to that of Fig. 19.16in the current example, though, the XHTML is stored on disk rather than generated dynamically by MSXML. After applying the transformation, the program displays the content of the new file sports.html in the txtConsole TextBox, as shown in Fig. 19.30(b). Line 23 obtains the text of the file by passing its name to method ReadAllText of the System.IO.File class provided by the FCL to simplify file-processing tasks on the local system. |