Java Reference
In-Depth Information
xmlDoc.append(getDocumentNode(doc.getDocumentElement(), ""));
This is for good reason. We will need a recursive method to navigate the nodes in the
Document
object
that represent the body of the document and create the XML for that. The string that is returned will be
the entire document body, so once we have appended this to
xmlDoc
we have the complete document.
We will implement the
getDocumentNode()
method shortly.
The other statement deserving some explanation is the one in the
try
block that writes the complete
document to the file:
channel.write(ByteBuffer.wrap(xmlDoc.toString().getBytes("UTF-8")));
Starting from the inside, and working outwards: Calling the
toString()
method for
xmlDoc
returns
the contents as type
String
. We then call the
getBytes()
method for the
String
object to obtain
an array of type
byte[]
containing the contents of the
String
object encoded as UTF-8. We then call
the static
wrap()
method in the
ByteBuffer
class (that will need importing) to create a
ByteBuffer
object that wraps the array. The buffer that is returned has its limit and position set ready for the buffer
contents to be written to a file. We can therefore pass this
ByteBuffer
object directly to the
write()
method for the
FileChannel
object to write the contents of the buffer, which will be the entire XML
document, to the file. How's that for a powerful statement.
The code for the
getDoctypeString()
method will be:
private String getDoctypeString(org.w3c.dom.DocumentType doctype) {
// Create the opening string for the DOCTYPE declaration with its name
String str = doctype.getName();
StringBuffer doctypeStr = new StringBuffer("<!DOCTYPE ").append(str);
// Check for a system ID
if((str = doctype.getSystemId()) != null)
doctypeStr.append(" SYSTEM ").append(QUOTE).append(str).append(QUOTE);
// Check for a public ID
if((str = doctype.getPublicId()) != null)
doctypeStr.append(" PUBLIC ").append(QUOTE).append(str).append(QUOTE);
// Check for an internal subset
if((str = doctype.getInternalSubset()) != null)
doctypeStr.append('[').append(str).append(']');
return doctypeStr.append(TAG
_
END).toString(); // Append '>' & return string
}
This is almost identical to the method as implemented in our previous example.