The Source Code
The transformation from XML to HTML is surprisingly simple! This is the brilliant thing about Java in general—it provides a great deal of power up front. The program is packaged as a single source code file called DomainTransform.java. This is based exclusively on Sun's excellent J2EE 1.4 tutorial.
The program contains a single class and takes two parameters: the stylesheet file and the XML file. The latter is parsed and the required HTML data is streamed to the console as shown earlier in Listing 2.
Listing 8 completes the bulk of the code.
Listing 8 The source code
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try { File stylesheet = new File(argv[0]); File datafile = new File(argv[1]); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(datafile); // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource stylesource = new StreamSource(stylesheet); Transformer transformer = tFactory.newTransformer(stylesource); StreamSource source = new StreamSource(document); StreamResult result = new StreamResult(System.out); transformer.transform(source, result);
The stylesheet and XML filenames are read in from the command line and used in the parsing process. It's that simple. The transformer object provides a method that allows the stylesheet to be used in conjunction with the XML file. The end result is the data illustrated earlier in Listing 2.
This data can also be piped into a text file if required. I did this during a run of the program, and the result is included in the file NMSData.html included in the source code for this article. This file can be loaded into a browser if required. I guess that's our little problem solved!