I need set the XmlEncoding (UTF-8) in a Dom Document object without use a Transformer with his "setOutputProperty(OutputKeys.ENCODING, "UTF-8")" method.
I don't want obtain the XML string using the Transform object because I am using a Xades XMLSignature library which uses a Document object to sign.
The problem is that for a Dom Document created as follow, his getXmlEncoding() method returns null.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
document.getXmlEncoding(); //Returns null
But after apply the following code, the XmlEncoding methoth of the new DOM Document returns UTF-8 (requeriment for my xades library). It's because the transformation process has added the encoding somehow. For performance reasons I want to avoid to execute this code.
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
DOMSource source = new DOMSource(document);
Writer writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String xml = writer.toString();
InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document newDocument = dbf.newDocumentBuilder().parse(inputStream);
newDocument.getXmlEncoding(); //returns "UTF-8"
How I can create the Dom Document with the prolog information?