Although DOM is a read-write API in memory, it's sorely lacking when it comes to moving its in-memory data structure back out onto a disk, a network socket, or some other stream. Eventually, this omission will be rectified in DOM3. In the meantime, you have the choice of using either implementation-specific serialization classes or JAXP. The implementation-specific serialization classes generally provide more customization and features, but JAXP is sufficient for basic uses. JAXP doesn't include a serialization package, but you can hack basic output through the javax.xml.transform package by conveniently " forgetting " to install a transform. :-) The pattern is the same as parsing a document with JAXP. The basic steps are as follows :
We can use this procedure to write a simple driver program for Example 9.12. Example 9.14 first uses JAXP to build a DOM Document object from a URL, then passes this object to the Restructurer.processNode() method, and finally serializes the whole document onto System.out . Example 9.14 Using JAXP to Read and Write an XML Documentimport javax.xml.parsers.*; // JAXP import javax.xml.transform.*; // JAXP import javax.xml.transform.dom.DOMSource; // JAXP import javax.xml.transform.stream.StreamResult; // JAXP import org.xml.sax.SAXException; import org.w3c.dom.Document; import java.io.IOException; public class RestructureDriver { public static void main(String[] args) { if (args.length <= 0) { System.out.println("Usage: java RestructureDriver URL"); return; } String url = args[0]; try { // Find a parser DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder parser = factory.newDocumentBuilder(); // Read the document Document document = parser.parse(url); // Modify the document Restructurer.processNode(document); // Write it out again TransformerFactory xformFactory = TransformerFactory.newInstance(); Transformer idTransform = xformFactory.newTransformer(); Source input = new DOMSource(document); Result output = new StreamResult(System.out); idTransform.transform(input, output); } catch (SAXException e) { System.out.println(url + " is not well-formed."); } catch (IOException e) { System.out.println( "Due to an IOException, the parser could not read " + url ); } catch (FactoryConfigurationError e) { System.out.println("Could not locate a factory class"); } catch (ParserConfigurationException e) { System.out.println("Could not locate a JAXP parser"); } catch (TransformerConfigurationException e) { System.out.println("This DOM does not support transforms."); } catch (TransformerException e) { System.out.println("Transform failed."); } } } You'll learn how to actually use these classes for their intended purposes of XSLT transformation in Chapter 17. |