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?
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.
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 .
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With