JAVA : Write XML Document with different encoding

If you've an xml built with org.w3c.dom.Document and you want to change encoding attribute from default UTF-8 to another (ie ISO-8859-1), the solution is:


ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document doc = mw.getMETSDocument();
DOMImplementation impl = doc.getImplementation();
DOMImplementationLS implLS = (DOMImplementationLS)impl.getFeature("LS","3.0");
LSOutput lso = implLS.createLSOutput();
lso.setEncoding("ISO-8859-1");
lso.setByteStream(baos);
LSSerializer writer = implLS.createLSSerializer();
writer.write(doc, lso);
String xml = baos.toString("ISO-8859-1");

In this case I used ByteArrayOutputStream, but you can also use StringWriter.

The result is:

<?xml version="1.0" encoding="ISO-8859-1"?>

If your xml content doesn't match this encoding, this exception will be raised:

Invalid byte 1 of 1-byte UTF-8 sequence 



Commenti