0

I'm using Spring Boot Java to prompt user to save an XML file.

My code is the following:

public class ExportE125Controller  {
 
    @Autowired
    @Qualifier("jdbcExportE125")
    private JdbcTemplate template;    
    
    @RequestMapping(path = "/exportE125",  method = RequestMethod.POST,
            consumes ="application/x-www-form-urlencoded; charset=utf-8")
    public ResponseEntity<byte[]> getE125New(@RequestParam Map<String, String> body,HttpServletRequest request, 
            HttpServletResponse response) throws ServletException, IOException
    {
        String str = "<?xml version="1.0" encoding="UTF-8"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>"
                
        byte[] output =str.getBytes("UTF-8");
        
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.set("charset", "utf-8");
        responseHeaders.setContentType(MediaType.valueOf("application/xml"));
        responseHeaders.setContentLength(output.length);
        responseHeaders.set("Content-disposition", "attachment; filename=file.xml");

        return new ResponseEntity<byte[]>(output, responseHeaders, HttpStatus.OK);

   }

The correct way of having the content of file.xml should be:

<?xml version="1.0" encoding="UTF-8"?>
   <note>
       <to>Tove</to>
       <from>Jani</from>
       <heading>Reminder</heading>
       <body>Don't forget me this weekend!</body>
   </note>
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
zinon
  • 4,427
  • 14
  • 70
  • 112
  • That's not "correct". That's just pretty-printed. Since you're already writing the string by hand, you could just as well pretty-print it by hand. Unless you're doing something more relevant. – Kayaman Feb 11 '22 at 14:30
  • @Kayaman Is there a way of pretty content within the xml file? – zinon Feb 11 '22 at 14:30
  • But you don't have an xml file, you have a hard coded String. You're not really even working with XML here, since you don't have any parsers involved. – Kayaman Feb 11 '22 at 14:31
  • 2
    Does this answer your question? [How to pretty print XML from Java?](https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) – pringi Feb 11 '22 at 14:38
  • @pringi unfortunately no. – zinon Feb 11 '22 at 15:04
  • You can use XSLT for XML file indentation. – Yitzhak Khabinsky Feb 11 '22 at 15:18
  • @pringi Finally using the proposed solution with minor modifications it worked. – zinon Feb 11 '22 at 17:43

0 Answers0