SpringBoot/Jackson how do I set standalone="yes" in XML prolog

432 Views Asked by At

I've created a bean to include an XML prolog in my Jackson XML responses.

@Bean
    public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) throws XMLStreamException {
        XmlMapper xmlMapper = builder.createXmlMapper(true).build();
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        
        return new MappingJackson2XmlHttpMessageConverter(xmlMapper);
    }

But, I need to include standalone="yes" in the prolog. I'm not sure how to add this additional attribute? My Spring Boot version is 3.0.6 and my Jackson version is 2.14.2

1

There are 1 best solutions below

4
Samir Lakhani On

To include the standalone="yes" attribute in the XML prolog using Spring Boot and Jackson, you can customize the XmlMapper configuration by providing a custom Jackson2ObjectMapperBuilder instance. Here's an updated version of your code that includes the standalone attribute:

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.http.converter.xml.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonXmlConfig {

    @Bean
    public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) {
        XmlMapper xmlMapper = builder.createXmlMapper(true).build();
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_0_BOM, false);
        xmlMapper.configure(ToXmlGenerator.Feature.STANDALONE, "yes"); // Set the standalone attribute
        
        return new MappingJackson2XmlHttpMessageConverter(xmlMapper);
    }

}

In this updated code, the xmlMapper.configure(ToXmlGenerator.Feature.STANDALONE, "yes") line sets the standalone attribute in the XML prolog to "yes". This will include the standalone="yes" attribute in the generated XML responses.

Please note that the ToXmlGenerator.Feature.STANDALONE feature is available starting from Jackson version 2.13.0. Since you mentioned that your Jackson version is 2.14.2, it should work fine.

Make sure to include this configuration class in your Spring Boot application or in the appropriate component scan location for it to take effect.