Search code examples
javaxmljaxbmarshalling

JAXB Marshal missing Attribute/Element


I have the following JAXB object:

@XmlRootElement(name = "AuthEntry")
@XmlAccessorType(XmlAccessType.FIELD)
public class AuthEntry {

    @XmlElement(name = "Account")
    private Account account;

    @XmlElement(name = "Key", required = true)
    private String key;

    @XmlElement(name = "Expire", required = true)
    private Date expire;

    // Getter & Setter
    // ...

I use the JAXB Marshaller to convert the object to XML:

public static <T> String marshalObject(T pObject) throws JAXBException, IOException {
    JAXBContext context = JAXBContext.newInstance(pObject.getClass());

    Marshaller m = context.createMarshaller();

    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        m.marshal(pObject, stream);
        stream.flush();

        return new String(stream.toByteArray());
    }
}

It runs smoothly without any exception, however, the result is always missing the Element Key. I tried to change it to Attribute instead, but it doesn't work too. Here is an example output:

<AuthEntry xmlns:ns2="urn:schemas-microsoft-com:sql:SqlRowSet3">
    <Account ID="1" Username="datvm" Password="datvm" FullName="NullPtrExc" Active="true"/>
    <Expire>2014-06-06T20:07:32.428+07:00</Expire>
</AuthEntry>

I have tried to change the Key name to another, such as AuthKey, but it is still missing. What did I do wrong?

EDIT I found the problem, it is because my Key value is null. If it contains value, then it is written to the XML. However, can you please explain why in the XMLElement, I wrote required = true, yet it still missing when it is null?


Solution

  • JAXB & null

    By default a JAXB implementation will not marshal an attribute or element for a null value. You can have JAXB generate an element that contains the xsi:nil="true" attribute using the following:

    @XmlElement(nillable=true)
    

    Empty Elements

    An empty element is not a valid representation for null. For example if your element was of type xs:dateTime and the corresponding element was empty, then that document would not validate against the XML schema.