Omitting the standalone attribute in xml declaration when using Java DOM + Transformer.

Viewed 21066

Is there any way to tell the Transformer (when serializing an XML document using DOM), to omit the standalone attribute?

Preferably without using a hack, i.e. ommitting the whole XML declaration and then prepending it manually.

My current code:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //Note nothing is changed

StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(document);
transformer.transform(source, result);
 return result.getWriter().toString();

Current:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<someElement/>

Intended:

<?xml version="1.0" encoding="UTF-8">
<someElement/>
4 Answers

You have to use a combination of:

doc.setXmlStandalone(true);

and

transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // this is used to show the standalone tag

Related