Search code examples
springspring-bootkotlinthymeleaf

How do you generate an XML with Thymeleaf in Spring Boot?


I have a web application I'm building with Spring Boot, Kotlin and Thymeleaf. I have some HTML templates working, but I want to make one return an XML file. This XML would be a Thymeleaf template, using Thymeleaf attributes. What's the correct way of doing that in Spring Boot? Also, the XML should be downloaded.

I've seen this: Spring Boot & Thymeleaf with XML Templates, but it seems that would switch Thymeleaf to generate XMLs site-wide, not just for a single controller.


Solution

  • Alright then, one way of doing it would be configuring the Thymeleaf engine in a single method. For example:

    @GetMapping("/xml")
    public void xml(HttpServletResponse res) throws Exception {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(new AnnotationConfigApplicationContext());
        resolver.setPrefix("classpath:/xml/");
        resolver.setSuffix(".xml");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setTemplateMode(TemplateMode.XML);
    
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(resolver);
    
        Context ctx = new Context();
        ctx.setVariable("notes", Arrays.asList("one note", "two note"));
        String xml = engine.process("template", ctx);
    
        res.setHeader("Content-Disposition", "attachment; filename=template.xml");
        res.setContentType("application/xml");
        PrintWriter writer = res.getWriter();
        writer.print(xml);
        writer.close();
    }
    

    Where the template is located in src/main/resources/xml/template.xml. You set your model variables using the ctx.setVariable() method.