FasterXML jackson-dataformat-xml serialization version and encoding not added to xml
You can configure your XmlMapper
to write the XML header.
XmlMapper xmlMapper = new XmlMapper();xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
As an example:
import com.fasterxml.jackson.dataformat.xml.XmlMapper;import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;import java.io.IOException;public class Xml { public static void main(String[] args) throws IOException { // Important: create XmlMapper; it will use proper factories, workarounds XmlMapper xmlMapper = new XmlMapper(); xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); xmlMapper.writeValue(System.out, new SampleRequest()); }}class SampleRequest{ public int x = 1; public int y = 2;}
This generates the output:
<?xml version="1.0" encoding="UTF-8"?><SampleRequest> ...</SampleRequest>
In case you want to set the version to 1.1 instead of 1.0, use ToXmlGenerator.Feature.WRITE_XML_1_1
.
Notice that Faster-XML team recommends to use Woodstox library. In case you use it, some other configurations can be set. Among all of them there is one related to setting double quotes:
public static final String P_USE_DOUBLE_QUOTES_IN_XML_DECL="com.ctc.wstx.useDoubleQuotesInXmlDecl";
For more details check out configuring Woodstox parser.
import com.ctc.wstx.api.WstxOutputProperties;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.json.Jackson2ObjectMapperBuilder;import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;@Configurationpublic class XmlConfig { @Bean public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter(Jackson2ObjectMapperBuilder builder) { XmlMapper xmlMapper = builder.createXmlMapper(true).build(); xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION); xmlMapper.getFactory().getXMLOutputFactory().setProperty(WstxOutputProperties.P_USE_DOUBLE_QUOTES_IN_XML_DECL, true); return new MappingJackson2XmlHttpMessageConverter(xmlMapper); }}