2
votes

There is a pseudo code like this:

Alma alma = new Alma();
alma.setKorte(""); //Korte is a string member
marshaller.marshal(alma, stringwriter);
System.out.println(stringwriter.toString());

And it produces the output of (I know this is some kind of trick that the empty element is there, but this is how it works in my system, so someone before me have set this like this):

<alma><korte/></alma>

Which is fine for me. But when I unmarshal it, the empty string is not unmarshalled correctly, but korte will be null. How to make jaxb to unmarshal the empty element into empty string?

I use JDK6 bundled jaxb.

EDIT:

The alma class looks like (name of class is changed, but it is like this):

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Alma", propOrder = {
    "korte"
})
public class Alma
    implements Serializable
{

    private final static long serialVersionUID = 100L;
    @XmlElement(required = true)
    protected String korte;
1
What does the Alma class look like? - skaffman

1 Answers

1
votes

JAXB implementations should unmarshal empty elements as "" for String properties. The solution will be to upgrade to a newer version of your JAXB implementation that contains this fix.

The example below worked for me using the version of JAXB included in JDK 1.6.0_20 and EcliseLink JAXB (MOXy) 2.3.

Demo

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Alma.class);

        String xmlString = "<alma><korte/></alma>";
        StringReader xmlReader = new StringReader(xmlString);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Alma alma = (Alma) unmarshaller.unmarshal(xmlReader);

        System.out.println(alma.getKorte().length());
    }

}

Output

0

Alma

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@XmlType(name = "Alma", propOrder = { "korte" })
public class Alma implements Serializable {

    private final static long serialVersionUID = 100L;

    @XmlElement(required = true)
    protected String korte;

    public String getKorte() {
        return korte;
    }

    public void setKorte(String korte) {
        this.korte = korte;
    }

}