2

I have an object which holds data of a person. When a user clicks on the download button the xml needs to be created by (person.dataitems) and after that user should have an option to download the file (like save file or open file)

I have written the code below which creates a xml file when the button is clicked however the file remains empty. I would like to know how I can write data to this file and then download.

response.setHeader( "Content-Disposition", "attachment;filename="+patient.getGivenName()+".xml");   
try {
    StringWriter r = new StringWriter();
    String ccdDoc = r.toString();
    ccdDoc = ccdDoc.replaceAll("&lt;", "<");
    ccdDoc = ccdDoc.replaceAll("&quot;", "\"");
    byte[] res = ccdDoc.getBytes(Charset.forName("UTF-8"));
    response.setCharacterEncoding("UTF-8");
    response.getOutputStream().write(res);
    response.flushBuffer();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Thanks.

Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
user1882758
  • 155
  • 3
  • 13

2 Answers2

4

You have to write into your StringWriter:

import java.io.*;

public class StringWriterDemo {

   public static void main(String[] args) {

      String s = "Hello World";

      // create a new writer
      StringWriter sw = new StringWriter();

      // write portions of strings
      sw.write(s, 0, 4);
      sw.write(s, 5, 6);
      // write full string
      sw.write(s);

      // print result by converting to string
      System.out.println("" + sw.toString());


   }
}

Do not do:

String ccdDoc = r.toString();

It only creates a copy of the r string. Then you are modifying the copy, but not at all the content of the StringWriter.

Do:

r.write("some content");

and to access the string contained by the writer, do:

String a_string = r.toString();
response.getOutputStream().write(a_string);

EDIT :

OK, so what you are asking is not so far from what you have in the link you provided, excepted that you have to write into a StringWriter instead of into a File.

This can be achieved this way:

1) Do build an xml document:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);

// staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);

// set attribute to staff element
staff.setAttribute("id", "1");

// firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);

:
:

// Then write the doc into a StringWriter

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

//initialize StreamResult with StringWriter object to save to string
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);

String xmlString = result.getWriter().toString();
System.out.println(xmlString);

// Finally, send the response

byte[] res = xmlString.getBytes(Charset.forName("UTF-8"));
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(res);
response.flushBuffer();


The point here is to do:

StreamResult result = new StreamResult(new StringWriter());

instead of:

StreamResult result = new StreamResult(new File("C:\\file.xml"));

You tell me if there is still something unclear in this.

Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85
  • I am trying to write into an XML file, so how do I use StringWriter to add elements to XML file. I went through this example: http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/ However this is saving the file directly in location. I want to provide an download option. – user1882758 Jun 27 '13 at 18:31
  • @user1882758 I updated my answer. Give it a try and tell me how it worked ;) – Gauthier Boaglio Jun 28 '13 at 00:05
  • You should just pass the `response.getOutputStream()` to the `new StreamSource(OutputStream)` constructor. The will cause the transformer to write straight to the servlet response output stream. – Paul Samsotha Aug 13 '18 at 07:56
0

it's worked

 byte[] res = xmlString.getBytes(Charset.forName("UTF-8"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader( "Content-Disposition", "attachment;filename=archivo.xml");
            response.getOutputStream().write(res);
            response.flushBuffer();