FasterXML jackson-dataformat-xml serialization version and encoding not added to xml

Sajith Vijesekara picture Sajith Vijesekara · Feb 15, 2016 · Viewed 13.5k times · Source

Hi I am serializing java POJO object to xml using faster-xml(https://github.com/FasterXML/jackson-dataformat-xml/wiki ).When i do that i got xml but it doesn't have any version and encoding in xml file.This is the format i need

<?xml version="1.0" encoding="utf-8"?>
<SampleRequest>
... 
</SampleRequest>

But I got Only this one

<SampleRequest>
... 
</SampleRequest>

Is there any configuration need to be added in jackson fasterxml anotation.

Answer

Ricard N&#224;cher Roig picture Ricard Nàcher Roig · Feb 15, 2016

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";

at WstxOutputProperties.java

For more details check out configuring Woodstox parser.