Add standalone directive to Jackson XML serialization

Viewed 1257

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?

1 Answers

I meet the same problem and I have resolved this problem by reloading the class BufferingXmlWriter (copy from source code and modify a method), the reloading must before that you use Jackson to produce an XML

  1. Create package com.ctc.wstx.sw and create class BufferingXmlWriter
  2. Copy source code from real com.ctc.wstx.sw.BufferingXmlWriter
  3. Modify method writeXmlDeclaration(String version, String encoding, String standalone)
public void writeXmlDeclaration(String version, String encoding, String standalone)
            throws IOException
 {
       // final char chQuote = (mUseDoubleQuotesInXmlDecl ? '"' : '\'');
        final char chQuote = '"';
    
        fastWriteRaw("<?xml version=");
        fastWriteRaw(chQuote);
        fastWriteRaw(version);
        fastWriteRaw(chQuote);
    
        if (encoding != null && encoding.length() > 0) {
            fastWriteRaw(" encoding=");
            fastWriteRaw(chQuote);
            fastWriteRaw(encoding);
            fastWriteRaw(chQuote);
        }
        if (standalone == null) {
            fastWriteRaw(" standalone=");
            fastWriteRaw(chQuote);
            fastWriteRaw("yes");
            fastWriteRaw(chQuote);
        }
        fastWriteRaw('?', '>');
 }    
  1. Reload

     Class.forName("com.ctc.wstx.sw.BufferingXmlWriter");
    
  2. Result

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