Calling XSLT from javascript

2020-02-06 04:30发布

问题:

I have a series of XML files which reference XSLT files to render as HTML in the browser. Some of these have links which would, on a regular page, perform an AJAX call to request HTML and insert it into a DIV already on the page.

What I want to do is call a webservice from this page, upon a link click, and receive XML which then is processed into HTML in just the same way as the original page was, and then inserted via AJAX into a DIV on the current page.

My question is: How would I get the XML which is downloaded by Javascript to be parsed by it's associated XSLT using Javascript?

回答1:

In MSIE you can call xmlDoc.transformNode(xslDoc). (Both xmlDoc and xslDoc are XML document objects, as may be loaded through e.g. XHR). In Opera, Firefox etc. you should construct an XSLTProcessor first (let's call it proc), then call proc.importStylesheet(xslDoc), and finally you can use on of the transformToXXX methods of XSLTProcessor. (E.g.: proc.transformToFragment(xmlDoc, document) to create a DOMDocumentFragment which may be inserted in the document object using an appropriate appendChild() call.)