title: How to create an empty DOCTYPE using W3C DOM in Java?
body: <p>I am trying to read an XML document and output it into a new XML document using the <a href="http://docs.oracle.com/javase/6/docs/api/org/w3c/dom/package-summary.html" rel="nofollow">W3C DOM API in Java</a>. To handle DOCTYPEs, I am using the following code (from an input Document <code>doc</code> to a target File <code>target</code>):</p>
  
  <pre><code>TransformerFactory transfac = TransformerFactory.newInstance();
  Transformer trans = transfac.newTransformer();
  trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // omit '&lt;?xml version="1.0"?&gt;'
  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);
  </code></pre>
  
  <p>This works fine for both XML documents with and without DOCTYPEs. However, I am now coming across a <code>NullPointerException</code> when trying to transform the following input XML document:</p>
  
  <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt;
  &lt;!DOCTYPE permissions &gt;
  &lt;permissions&gt;
    // ...
  &lt;/permissions&gt;
  </code></pre>
  
  <p>HTML 5 uses a similar syntax for its DOCTYPEs, <a href="http://en.wikipedia.org/wiki/Document_Type_Declaration#HTML5_DTD-less_DOCTYPE" rel="nofollow">and it is valid</a>. But I have no idea how to handle this using the W3C DOM API - trying to set the <code>DOCTYPE_SYSTEM</code> to <code>null</code> throws an exception. Can I still use the W3C DOM API to output an empty doctype?</p>