private static void doSerialize(OutputStream outputStream, Document document, String encoding)
{
try
{
Transformer transformer = new DefaultJAXPConfiguration().createTransformer(encoding);
// Be sure to use actual encoding of the transformer which might be non-null even if encoding started as null.
encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
Writer writer = encoding == null ? new OutputStreamWriter(outputStream) : new OutputStreamWriter(outputStream, encoding);
transformer.transform(new DOMSource(document), new StreamResult(writer));
}