Set XmlEncoding to Dom Document in Java

415 views Asked by At

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?

1

There are 1 answers

0
Andreas Veithen On

You could try using Apache Axiom's DOM implementation. It implements both the DOM API and Axiom's own API, which actually allows setting the XML encoding. Simply add axiom-dom to your project and use the following instruction to get a DocumentBuilderFactory:

DocumentBuilderFactory factory = ((DOMMetaFactory)OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM)).newDocumentBuilderFactory();

You can then set the XML encoding on a document as follows:

((OMDocument)document).setXMLEncoding("utf-8");

The rest of your code remains unchanged and can continue using the DOM API.