Java Reference
In-Depth Information
The Serializer class in nu.xom offers control over how an XML document is formatted
when it is displayed or stored serially. Indentation, character encoding, line breaks, and
other formatting are established by objects of this class.
A Serializer object can be created by specifying an output stream and character encod-
ing as arguments to the constructor:
File inFile = new File(arguments[0]);
FileOutputStream fos = new FileOutputStream(“new_” +
inFile.getName());
Serializer output = new Serializer(fos, “ISO-8859-1”);
These statements serialize a file using the ISO-8859-1 character encoding. The file is
given a name based on a command-line argument.
Serializer supports 20 encodings, including ISO-10646-UCS-2, ISO-8859-1 through
ISO-8859-10, ISO-8859-13 through ISO-8859-16, UTF-8, and UTF-16. There's also a
Serializer() constructor that takes only an output stream as an argument; this uses the
UTF-8 encoding by default.
Indentation is set by calling the serializer's setIndentation() method with an integer
argument specifying the number of spaces:
output.setIndentation(2);
An entire XML document is written to the serializer destination by calling the serializer's
write() method with the document as an argument:
output.write(doc);
The DomainWriter application inserts a comment atop the XML document instead of
appending it at the end of a parent node's children. This requires another method of the
parent node, insertChild() , which is called with two arguments—the element to add
and the integer position of the insertion:
Builder builder = new Builder();
Document doc = builder.build(arguments[0]);
Comment timestamp = new Comment(“File created “ +
new java.util.Date());
doc.insertChild(timestamp, 0);
The comment is placed at position 0 atop the document, moving the domains tag down
one line but remaining below the XML declaration.
Listing 19.6 contains the source code of the application.
Search WWH ::




Custom Search