Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 832
Massimiliano Fliri Avatar asked Sep 11 '09 08:09

Massimiliano Fliri


People also ask

What is the use of <DOCTYPE> declaration?

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.

How to create a documenttype using DOM?

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.

Does <DOCTYPE> need a DTD in HTML?

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.

How do I declare a DOCTYPE in HTML5?

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.


1 Answers

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/>
like image 83
McDowell Avatar answered Nov 05 '22 10:11

McDowell