I have a DOM Document created from scratch and I need to serialize it to an output stream. I am using DOM level 3 serialization API, like in the following example:
OutputStream out;
Document doc;
DOMImplementationLS domImplementation =
(DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder().getDOMImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
LSOutput lsOutput = domImplementation.createLSOutput();
lsOutput.setByteStream(out);
lsSerializer.write(doc, lsOutput);
I need to have inside the resulting document a DOCTYPE declaration with both public and system identifiers, but I was not able to find a way to produce it.
How can I do?
The HTML <!DOCTYPE> declaration is not an HTML element or tag. It is an instruction that tells the browser what type of document to expect. All HTML documents need to start with a <!DOCTYPE> declaration. The declaration varies depending on what version of HTML the document is written in.
Document.doctype Returns the Document Type Declaration (DTD) associated with current document. The returned object implements the DocumentTypeinterface. Use DOMImplementation.createDocumentType()to create a DocumentType.
HTML5 is not based on SGML, and therefore does not require a reference to a DTD. Tip: Always add the <!DOCTYPE> declaration to your HTML documents, so that the browser knows what type of document to expect.
In HTML5, the doctype declaration is <!DOCTYPE html>. This is easy to write and remember, particularly when compared to the complicated doctype declarations of previous versions of HTML. The <!DOCTYPE> declaration is not case sensitive.
You can create a DocumentType
node using the DOMImplementation.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
// create doc
Document doc = docBuilder.newDocument();
DOMImplementation domImpl = doc.getImplementation();
DocumentType doctype = domImpl.createDocumentType("web-app",
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN",
"http://java.sun.com/dtd/web-app_2_3.dtd");
doc.appendChild(doctype);
doc.appendChild(doc.createElement("web-app"));
// emit
System.out.println(((DOMImplementationLS) domImpl).createLSSerializer()
.writeToString(doc));
Result:
<?xml version="1.0" encoding="UTF-16"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With