Java 2EE and XML Development

Скачать в pdf «Java 2EE and XML Development»


Listing 2.8 Building a DOM with JAXP


Imports the JAXP DOM classes


import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import java.io.File;


public class JAXPandDOM {


public static void main(String[] args) {


try {


DocumentBuilderFactory factory


= DocumentBuilderFactory.newInstance();


}



DocumentBuilder builder


= factory.newDocumentBuilder(); File ourExample


= new File(«product-catalog.xml» Document document


= builder.parse( ourExample );


} catch (Exception e) { System.out.println(e.getMessage());


}



Obtains a DOMBuilder via JAXP



Parses the XML and builds a DOM tree


}


Using JAXP with XSLT


JAXP supports XSLT in the same implementation-independent manner as XML parsing. The JAXP interfaces to XSLT are located in the javax.xml.transform package. The primary classes and interfaces are summarized in table 2.5. In addition to these top-level interfaces, JAXP includes three subpackages to support the use of SAX, DOM, and I/O streams with XSLT. These packages are summarized in table 2.6.


Table 2.5 Primary JAXP interfaces to the XSLT API


JAXP class or interface


Description


javax.xml.transform.TransformerFactory


Locates a TransformerFactory implementation class and instantiates it.


javax.xml.transform.Transformer


Interface to the underlying XSLT processor.


javax.xml.transform.Source


An interface representing an XML data source to be transformed by the Transformer.


javax.xml.transform.Result


An interface to the output of the Transformer after XSLT processing.

In section 2.1.3, we discussed the XSLT process and saw how our product catalog document could be transformed into HTML via XSLT. Now we examine how that XSLT process can be invoked from your Java code via JAXP. For the sake of clarity and simplicity, we will use the I/O stream helper classes from the javax.xml.transform.stream package to create our Source and Result objects.

Скачать в pdf «Java 2EE and XML Development»