2009-09-11 10 views
8

Ich habe ein DOM-Dokument von Grund auf neu erstellt und ich muss es zu einem Ausgabestream serialisieren. Ich bin mit DOM Level 3-Serialisierung-API, wie im folgende Beispiel:Wie kann eine DOCTYPE-Deklaration mit der Serialisierungs-API der DOM-Ebene 3 erstellt werden?

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); 

ich mit in dem resultierenden Dokument eine DOCTYPE-Deklaration sowohl öffentlichen als auch System-IDs haben muß, aber ich war nicht in der Lage, einen Weg zu finden, um produziere es.

Wie kann ich tun?

Antwort

13

Mit der DOMImplementation können Sie einen DocumentType Knoten erstellen.

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)); 

Ergebnis:

<?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/> 
+0

Wie die Kodierung UTF-8 ändern? –

+1

@ VishnuPrasadKallummel Sehen Sie die Verwendung von [LSOutput] (http://docs.oracle.com/javase/8/docs/api/org/w3c/dom/ls/LSOutput.html) in [dieser Antwort] (http://stackoverflow.com/a/28546725/304). – McDowell