Java Reference
In-Depth Information
String str = doctype.getName();
StringBuffer doctypeStr = new StringBuffer("<!DOCTYPE ").append(str);
This will produce a string of the form "
<!DOCTYPE rootname
". We can now append any further bits
of the declaration to this string and close it off with a '
>
' character at the end.
We have defined the char constant,
QUOTE
, to make the code a little easier to read. We use this when
we check for a system ID or a public ID:
if((str = doctype.getSystemId()) != null)
doctypeStr.append(" SYSTEM ").append(QUOTE).append(str).append(QUOTE);
else if((str = doctype.getPublicId()) != null) // Check for a public ID
doctypeStr.append(" PUBLIC ").append(QUOTE).append(str).append(QUOTE);
This reuses the
str
variable to store the reference returned by the
getSystemID()
method. If this is
not
null
, we append the
SYSTEM
keyword followed by the system ID itself, inserting the necessary
spaces and double quotes at the appropriate points. Otherwise we look for a public ID and if it exists we
append that to the string in a similar fashion.
Next we check for an internal subset of definitions:
if((str = doctype.getInternalSubset()) != null)
doctypeStr.append('[').append(str).append(']');
If there is an internal subset string we append that too, topped and tailed with square brackets. The final
step is to append a closing
'>'
character and create a
String
object from the
StringBuffer
object
before returning it.
return doctypeStr.append('>').toString(); // Append '>' and return the string
I'll bet that was a whole lot easier than you expected. We will now put DOM into reverse and look into
how we can synthesize XML documents.
Creating XML Documents
You can create an XML document in a file programmatically by a two-step process. You can first create
a
Document
object that encapsulates what you want in your XML document. Then you can use the
Document
object to create the hierarchy of elements that has to be written to the file. We will first look
at how we create a suitable
Document
object.
The simplest way to create a
Document
object programmatically is to call the
newDocument()
method for
a
DocumentBuilder
object and it will return a reference to a new empty
Document
object:
Document newDoc = builder.newDocument();
This is rather limited, especially since there's no way with DOM2 to modify the
DocumentType
node
to reflect a suitable
DOCTYPE
declaration.