jeremy
jeremy

Reputation: 914

How to force Jackson to close an empty XML element?

I'm trying to serialize simple objects to XML using Jackson but I'm having trouble closing empty XML elements. I get this

<SimplePojo name="simpleName">
</SimplePojo>

but I want this

<SimplePojo name="simpleName"/>

If there's a setting for it, I can't find it. Any help will be greatly appreciated.


public class SimplePojo
{
    public SimplePojo(String name)
    {
        this.name = name;       
    }

    @JacksonXmlProperty(isAttribute = true)
    private String name;

    public String getName()
    {
        return this.name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    @JsonInclude(Include.NON_EMPTY) 
    private String property;

    public String getProperty()
    {
        return property;
    }

    public void setProperty(String property)
    {
        this.property = property;
    }
}

and I'm using the class like this:

 JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(false);

    XmlMapper xmlMapper = new XmlMapper(module); 
    xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    SimplePojo simple = new SimplePojo("simpleName");
    //simple.setProperty("something");

    String res = xmlMapper.writeValueAsString(simple);

EDIT: Here is a list of the jars I'm using

Jackson jars

Upvotes: 4

Views: 3317

Answers (2)

yunspace
yunspace

Reputation: 2570

I also came across this issue using both 2.3.1 and 2.2.3 versions of jackson-data-format-xml. Managed to resolve it by adding the same Woodstox jars as you. So pretty sure the fix isn't indentation related.

If you are not sure if you are using Woodstox, you explicitly create a woodstox XMLFactory and use it in your XMLMapper

XmlFactory xmlFactory = new XmlFactory(new WstxInputFactory(), new WstxOutputFactory());
XmlMapper mapper = new XmlMapper (xmlFactory, module);

Good luck!

Upvotes: 1

StaxMan
StaxMan

Reputation: 116472

One possible thing to try is to make sure you use Woodstox as your Stax implementation and NOT the default one JDK provides (Sun's SJSXP). Woodstox is better all-around, and I think it also implicitly uses empty elements if possible, whereas SJSXP I think does not.

Upvotes: 0

Related Questions