Java Reference
In-Depth Information
to identify the document's root node. If no root node is set, then a transform operation creates an empty
Document
object for use as the source.
A
StreamSource
object encapsulates an input stream that is a source of XML markup. This implies that
a file containing XML can be a source for a transformation. There are
StreamSource
constructors that cre-
ate objects from a
File
object, an
InputStream
object, a
Reader
object, or a
String
specifying a URL
that identifies the input stream. Here's how you could create a
StreamSource
object from an
InputStream
object:
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java
Stuff").resolve("Address.xml");
try(BufferedInputStream xmlIn = new
BufferedInputStream(Files.newInputStream(file))) {
StreamSource source = new StreamSource(xmlIn);
// Code to use the source...
} catch (IOException e) {
e.printStackTrace();
}
You just pass the
xmlIn
stream object to the
StreamSource
constructor to make the file the source for a
transform operation. You create
xmlIn
from the
Path
object,
file
, in the way you have seen several times
before. The
try
block is necessary for the stream operations, not for the
StreamSource
constructor.
The
Result
interface is implemented by six classes, but I'm only introducing
javax.xml.transform.dom.DOMResult
and
StreamResult
from the
javax.xml.transform.stream
package. A
DOMResult
object encapsulates a
Document
object that results from a transformation of a
Source
object. A
StreamResult
object encapsulates an output stream, which could be a file or just the command
line, and the markup that results from a transformation is written to the stream. Creating
DOMResult
and
StreamResult
objects is similar to creating source objects.
Both the source and destination for a
transform()
operation can be either a
Document
object or a stream,
so you can use a transform to transfer the XML contained in a
Document
object to a file or to create a
Docu-
ment
object from a file that contains XML markup. Suppose that you have a
Document
object,
xmlDoc
, that
you want to write to a file. Here's how you could use a
Transformer
object to do it:
Path file = Paths.get(System.getProperty("user.home")).
resolve("Beginning Java Stuff").resolve("MyXMLDoc.xml");
try(BufferedOutputStream xmlOut = new
BufferedOutputStream(Files.newOutputStream(file))) {
// Create a factory object for XML transformers
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
// Make the transformer indent the output
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Create the source and result objects for the transform
DOMSource source = new DOMSource(xmlDoc.getDocumentNode());
StreamResult xmlFile = new StreamResult(xmlOut);
transformer.transform(source, xmlFile); // Execute transform
} catch (TransformerConfigurationException tce) {