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");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
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?