Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add standalone directive to Jackson XML serialization

I'm trying to get Jackson to produce an XML header like JAXB does, but I can't figure out how to add the "standalone='yes'?"

Example:

public class XmlTest {

    @XmlRootElement
    public static class Book {

    }

    @Test
    public void testBookXml() throws JsonProcessingException {
        XmlMapper mapper = new XmlMapper();
        mapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);

        System.out.println("Jackson\n" + mapper.writeValueAsString(new Book()) + "\n");

        StringWriter sw = new StringWriter();
        JAXB.marshal(new Book(), sw);
        System.out.println("JAXB\n" + sw.toString());
    }
}

The output is this:

Jackson
<?xml version='1.0' encoding='UTF-8'?><Book/>

JAXB
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book/>

I don't care about <Book/> vs <book/>. Other than String manipulation, is there a way to get the Jackson header to be like the JAXB one?

like image 555
PunDefeated Avatar asked Mar 15 '26 02:03

PunDefeated


1 Answers

If you want exactly as JaxB then solution provided by @gongxiansheng would work.

But if you are looking for double quoted XML declaration like me and have default Woodstox dependency then below setting will just be fine:

    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);  // for Pretty print or formatting
    xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
    xmlMapper.getFactory().getXMLOutputFactory().setProperty(WstxOutputProperties.P_USE_DOUBLE_QUOTES_IN_XML_DECL, true);
    String reqXml = xmlMapper.writeValueAsString(new MyRequestDetail());

This will result in double quoted xml declaration:

<?xml version="1.0" encoding="UTF-8"?>

Note: More configurations are listed here on this excellent article: Configuring Woodstox XML parser: Woodstox-specific properties

like image 105
rahulkesharwani Avatar answered Mar 17 '26 16:03

rahulkesharwani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!