XSLT comes in as a simple, yet powerful tool that can satisfy this requirement. It represents a set of transformation rules that, when applied to an XML document, instruct how to convert data from one format into another one. The latter format is familiar to the rest of the application and it is able to use it internally.
Instances of DOMParser and XSLTProcessor will be used throughout examples. Although not standardized, they are available in all modern browsers. This excludes Internet Explorer 8 and lower, where an alternative DOM parser implementation exists.
The first step is to construct objects that will be used.
var domParser = new DOMParser(); var xsltProcessor = new XSLTProcessor();
For simplicity, code fragments will assume that this step has already happened and that XML is stored in memory in its simplest form: as a string. The raw text needs to be converted to an actual DOM representation and that work is done by the DOM parser object. Finally, the new XML document object must be sent to the XSLT processor object to finalize its initialization.
var xsltText = "..."; var xsltDoc = domParser.parseFromString(xsltText, "text/xml"); xsltProcessor.importStylesheet(xsltDoc);
At this point, the XSLT processor is prepared and a reference to it should be kept safe, since there’s no need to re-create the same object over and over again. Everything is now ready to transform XML data.
Bear in mind that if the application has multiple data sources, each with its own XML format, then a separate XSLT processor object needs to be created for each one of them. The application should be smart enough to use the appropriate processor based on the data source.
So, once again, the input XML was downloaded, stored into memory as a string and converted into a DOM object. The difference this time is that XSLT processor takes this new XML object, applies transform rules to it and returns a document fragment as the final result.
var xmlText = "..."; var xmlDoc = domParser.parseFromString(xmlText, "text/xml"); var fragment = xsltProcessor.transformToFragment(xmlDoc, document);
Benefit from choosing this approach is that the developer has complete control of the output format and thus can significantly speed up development. Additional advantage is native implementation of transformation objects and their methods, which execute faster than DOM object methods. This feature will probably be the most noticeable on mobile devices.
(image source: Wikipedia)