How can produce a DOCTYPE declaration with DOM level 3 serialization API?
Asked Answered
E

1

8

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?

Esque answered 11/9, 2009 at 8:30 Comment(0)
K
13

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/>
Konstantin answered 11/9, 2009 at 9:7 Comment(2)
How to change the encoding to UTF-8?Votive
@VishnuPrasadKallummel See the use of LSOutput in this answer.Konstantin

© 2022 - 2024 — McMap. All rights reserved.