3
transformer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(System.out, "UTF-8")));

I'm using this to generate the output to console. I want to store the output to a sting. I don't know how to do. Can any one help me? :(

Thanks in advance

nixon1333
  • 531
  • 1
  • 9
  • 23

3 Answers3

7

For example use this (it avoids encoding the string):

StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String str = writer.getBuffer().toString();
clearwater
  • 514
  • 2
  • 7
  • `toString()` of `StringWriter` already goes to the buffer so: `String str = writer.toString();` – Sonata Aug 11 '17 at 14:30
2

Use StringWriter class instead of OutputStreamWriter.

Hakan Serce
  • 11,198
  • 3
  • 29
  • 48
0

One solution could look like this:

ByteArrayOutputStream out = new ByteArrayOutputStream();
transformer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(out, "UTF-8")));
String string = new String(out.toByteArray(), "UTF-8");
Tom
  • 3,913
  • 19
  • 28