views:

137

answers:

1

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?

+2  A: 

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"&gt;
<web-app/>
McDowell