Add the following XML declaration when returning xml as HTTP response in spring-boot.
<?xml version='1.0' encoding='UTF-8'?>
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
Application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
@SpringBootApplication
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping(value = "/xml", produces = { MediaType.TEXT_XML_VALUE })
public XmlResponse xml() {
return new XmlResponse();
}
@Bean
public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) {
XmlMapper xmlMapper = builder.createXmlMapper(true).build();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
return new MappingJackson2XmlHttpMessageConverter(xmlMapper);
}
}
<?xml version='1.0' encoding='UTF-8'?>
<XmlResponse>
<id>aa</id>
</XmlResponse>
How to add XML declaration in the xml returning from the end-point almost copy and paste.