27

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/>
Michael Currie
  • 13,721
  • 9
  • 42
  • 58
vicsz
  • 9,552
  • 16
  • 69
  • 101

4 Answers4

52

Figured it out..

Instead of changes to the transformer,

I add the following to the document object.

  document.setXmlStandalone(true);
vicsz
  • 9,552
  • 16
  • 69
  • 101
  • 7
    Why does that even work? According to the spec: https://www.w3.org/TR/2004/REC-xml-20040204/#sec-rmd "If there are external markup declarations but there is no standalone document declaration, the value "no" is assumed." This answer: https://stackoverflow.com/questions/5578645/what-does-the-standalone-directive-mean-in-xml also states that if standalone attribute is missing then "no" is assumed. Then how come document.setXmlStandalone(true); removes the attribute? – mdzh Jun 21 '17 at 13:58
3

document.setXmlStandalone(true/false); is working OK.

Anthony
  • 12,177
  • 9
  • 69
  • 105
JackBauer
  • 135
  • 1
  • 3
  • 10
2

You have to use a combination of:

doc.setXmlStandalone(true);

and

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

Rod Lima
  • 1,509
  • 26
  • 30
0

Which Java version are you using and/or which XSLT transformer? With Sun Java 1.6.0_16, the standalone attribute is only set in the output document if you set the output property and the content is also correct.

jarnbjo
  • 33,923
  • 7
  • 70
  • 94