JAVA Transformer adding spaces and single quotes t

2019-08-25 03:31发布

I have the following JAXB marshaller that is using a DOM result in order to add XML Digital Signature later on:

JAXBContext jaxbContext = JAXBContext.newInstance(DataPDU.class);
DataPDU myDataPDU = new DataPDU();
myDataPDU.setRevision("2.0.6");

// marshall the file
Marshaller marshaller = jaxbContext.createMarshaller();

DOMResult domResult = new DOMResult();
marshaller.marshal(myDataPDU, domResult);

// get the document list
Document document = (Document) domResult.getNode();

// create the output file
File kadSignatureOutputFile = new File("pptExampleTest.xml");

// create the file output stream to be used in the XSL transformation
OutputStream os = new FileOutputStream(kadSignatureOutputFile);

// create the factory and the transformer
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();

// set the document to print the out with indent and UTF-8 encoded
trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
trans.setOutputProperty(OutputKeys.INDENT, "yes");

// transform the DOM source to a stream source (i.e the file we are in)
trans.transform(new DOMSource(document), new StreamResult(os));

I have some problems here, the output file is not being encoded in UTF-8, even though the encoding is set to UTF-8 but in notepad++ it is not being marked as encoded and the software provides an option to convert the file to utf-8.

How to make sure the file is properly encoded when it is transformed by the JAVA API?

Another thing, the xml header attribute values are being single quoted and have space between the attribute name and value, I am not sure if this tag (the XML header) will be considered when signing the document later on, but if it does this is gonna be a big problem.

How to obtain the standard XML header with double quotes and no spaces using transformers?

Result:

<?xml version = '1.0' encoding = 'UTF-8'?>

Expectation:

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

0条回答
登录 后发表回答