Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

dom

xml

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/>
like image 872
vicsz Avatar asked Nov 05 '09 18:11

vicsz


People also ask

What is standalone attribute in XML declaration?

The XML standalone element defines the existence of an externally-defined DTD. In the message tree it is represented by a syntax element with field type XML. standalone. A value of no indicates that this XML document is not standalone, and depends on an externally-defined DTD.

What is XML DOM in Java?

DOM is an acronym stands for Document Object Model. It defines a standard way to access and manipulate documents. The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated.


3 Answers

Figured it out..

Instead of changes to the transformer,

I add the following to the document object.

  document.setXmlStandalone(true);
like image 174
vicsz Avatar answered Oct 01 '22 11:10

vicsz


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

like image 27
JackBauer Avatar answered Oct 04 '22 11:10

JackBauer


You have to use a combination of:

doc.setXmlStandalone(true);

and

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

like image 43
Rod Lima Avatar answered Sep 30 '22 11:09

Rod Lima