How to create an empty DOCTYPE using the W3C DOM in Java?

I am trying to read an XML document and output it to a new XML document using the W3C DOM API in Java . To process DOCTYPE, I use the following code (from the input document docto the target file target):

TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // omit '<?xml version="1.0"?>'
trans.setOutputProperty(OutputKeys.INDENT, "yes");

// if a doctype was set, it needs to persist
if (doc.getDoctype() != null) {
    DocumentType doctype = doc.getDoctype();
    trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
    trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
}

FileWriter sw = new FileWriter(target);
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);

This is great for both XML documents with and without DOCTYPE. However, I now encounter NullPointerExceptionwhen trying to convert the following XML input document:

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE permissions >
<permissions>
  // ...
</permissions>

HTML 5 uses the same syntax for its DOCTYPE and it is valid . But I have no idea how to handle this using the W3C DOM API - trying to install DOCTYPE_SYSTEMon nullthrows an exception. Can I use the W3C DOM API to output a blank document?

+3
2

, , , , , . . HTML5 XSLT, http://www.w3.org/html/wg/drafts/html/master/syntax.html#doctype-legacy-string,

HTML, HTML DOCTYPE "<!DOCTYPE html>", DOCTYPE ​​ DOCTYPE [...]

, <!DOCTYPE html SYSTEM "about:legacy-compat"> <!DOCTYPE html SYSTEM 'about:legacy-compat'>, .

Java, :

trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "about:legacy-compat");
+4

fooobar.com/questions/369026/.... , , Java DOM.

StAX

    XMLStreamWriter xmlStreamWriter =
        XMLOutputFactory.newFactory().createXMLStreamWriter( System.out, doc.getXmlEncoding() );
    Result result = new StAXResult( xmlStreamWriter );
    // ... create dtd String 
    xmlStreamWriter.writeDTD( dtd );
    DOMSource source = new DOMSource( doc );
    trans.transform( source, result );

, DTD String, DocumentType.

+1

All Articles