Luke Vo
Luke Vo

Reputation: 20638

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?

Upvotes: 4

Views: 5575

Answers (3)

salerokada
salerokada

Reputation: 383

I experienced same problem with field missing when marshaled. The field was not null (originally).
When debugged I find that in jaxbContext.typeMap.myFieldParrentClass.value.properties.singleElementLeafPropertyForMyField.hiddenByOverride = true.
I had parent class and child classes. Field was both in parent and child classes and correct value from parent would be overwritten by null from child class field.

Upvotes: 0

bdoughan
bdoughan

Reputation: 148977

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.

Upvotes: 2

nif
nif

Reputation: 3442

JAXB ignores the required attribute, see this question and answer.

However, if you create a XSD schema from your classes using schemagen, the required attribute of the annotation is honored and the XML element will be required according to the schema.

Upvotes: 2

Related Questions