Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove standalone attribute declaration in xml document?

Tags:

java

dom

xml

Im am currently creating an xml using Java and then I transform it into a String. The xml declaration is as follows:

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); doc.setXmlVersion("1.0"); 

For transforming the document into String, I include the following declaration:

TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); 

And then I do the transformation:

StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); String xmlString = sw.toString(); 

The problem is that in the XML Declaration attributes, the standalone attribute is included and I don't want that, but I want the version and encoding attributes to appear:

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

Is there any property where that could be specified?

like image 242
user1084509 Avatar asked Dec 08 '11 21:12

user1084509


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.

Is <? XML required?

Only the version is mandatory. Also, these are not attributes, so if they are present they must be in that order: version , followed by any encoding , followed by any standalone .

What is declaration in XML?

XML declaration contains details that prepare an XML processor to parse the XML document. It is optional, but when used, it must appear in the first line of the XML document.


1 Answers

From what I've read you can do this by calling the below method on Document before creating the DOMSource:

doc.setXmlStandalone(true); //before creating the DOMSource 

If you set it false you cannot control it to appear or not. So setXmlStandalone(true) on Document. In transformer if you want an output use OutputKeys with whatever "yes" or "no" you need. If you setXmlStandalone(false) on Document your output will be always standalone="no" no matter what you set (if you set) in Transformer.

Read the thread in this forum

like image 192
Aravind Yarram Avatar answered Sep 22 '22 10:09

Aravind Yarram