0

I am creating a custom XML document. But I do not want the XML to be available as a file but I want it to be available in the system clipboard as a string so that I can paste manually to an already existing file.

I am using the transformer to write the XML as :

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);

StringWriter writer = new StringWriter();
transformer.transform(source, new StreamResult(writer));
String output = writer.toString();

but I am getting a null pointer exception here.

transformer.transform(source, new StreamResult(writer));

Can you please help me out.

Migol
  • 8,161
  • 8
  • 47
  • 69
Vishnukk
  • 524
  • 2
  • 11
  • 27
  • Presumably `source` or `writer` are null. Use a debugger and let us know which it is. – Duncan Jones Mar 28 '14 at 09:11
  • Did you debug and check what is null? Is this your complete code and the actual line where the NPE occurs? The line looks fine to me (assuming `transformerFactory.newTransformer()` doesn't return null) and thus I'd assume the NPE occurs somewhere _inside_ the `transform()` method, e.g. because `doc` is null - however, your post doesn't say so, thus please double check. – Thomas Mar 28 '14 at 09:11
  • So your question is: "How to I put a String on the clipboard." –  Mar 28 '14 at 09:12

1 Answers1

1

Check this

TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

from here

Community
  • 1
  • 1
Gowthami Reddy
  • 430
  • 7
  • 23