XSLT – On the Client

To transform the document into XHTML in a browser, we can use XSLT.

A JavaScript Solution:

To transform a document from XML to XHTML, we can add an XSL stylesheet to the XML file and the browser will do the transformation. But, including a style sheet reference in an XML file will not work in a non XSLT aware browser and is thus not always desirable. JavaScript can be used to do the transformation as a more versatile solution and it also allows the browser-specific testing along with the use of different style sheets according to the browser and user needs. We can consequently transform data from one format to another using XSLT, also supporting different browsers and different user needs.

The XML File and the XSL File:

Books.xml:




  
    ABC
    Author Name
    2020
    100.00
  

  
    XQuery Book
    Author 1
    Author 2
 2005
    300.00
  

  
    Sociology 1
    Author Name
 2010
    250.00
  

  
    Current Affairs
    Author Name
 2004
    500.00
  

  
    Science Book
    Author 1
    Author 2
    Author 3
 2011
    150.00
  


XSL style sheet:




 

  

List of Books

Title Price

Explanation:

In the above XML file, there is no reference to the XSL file. It can thus be concluded that an XML file could be transformed using many different XSL style sheets.

Transforming XML to XHTML in the Browser:

Example:







Output:

Explanation:

In the above example, we are transforming the XML file to XHTML on the client. The loadXMLDoc() function can be used to create an XMLHttpRequest object, to use the open() and send() methods of the XMLHttpRequest object to send a request to a server and to get the response data as XML data. Here, we are displaying the XML file styled by the XSL file using the displayResult() function. For this, we need to first load the XML and XSL files. Now, we need to test the type of browser. If the browser is Internet Explorer, we will use the transformNode() method to apply the XSL style sheet to the XML document and to contain the styled XML document, we will set the body of the current document (id=”example”). If there are any other browsers, we will create a new XSLTProcessor object and import the XSL file to it. After which, we will use the transformToFragment() method to apply the XSL style sheet to the XML document and to contain the styled XML document, we will set the body of the current document (id=”example”).