how to set default value for element if that element is absent in xml file through jaxb unmarshalling in java


The issue is I want to set a default value for "name" element which is absent in input.xml file.How can I achieve this through jaxb?, I dont want to do it through java model. Is there a way to get it through shema or through jaxb. Below is the code:

1. customer.xsd

<xs:schema xmlns:xs="">

    <xs:element name="customer">
                <xs:element name="name" type="stringMaxSize5" minOccurs="0" default="ss"/>
                <xs:element name="phone-number" type="xs:integer" minOccurs="0" default="200" />
    <xs:simpleType name="stringMaxSize5">
        <xs:restriction base="xs:string">
            <xs:maxLength value="5"/>


2. Customer.model

@XmlType(name = "", propOrder = {
@XmlRootElement(name = "customer")
public class Customer {

    @XmlElement(defaultValue = "ss")
    protected String name;
    @XmlElement(name = "phone-number", defaultValue = "200")
    protected BigInteger phoneNumber;
    public String getName() {
        return name;
    public void setName(String value) { = value;
    public BigInteger getPhoneNumber() {
        return phoneNumber;
    public void setPhoneNumber(BigInteger value) {
        this.phoneNumber = value;

3. input.xml



For unmarshalling using the below code:

SchemaFactory sf =SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("customer.xsd"));

JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(new File("input.xml"));
System.out.println(customer.getName() + "   " + customer.getPhoneNumber());

By running this I am getting null value for the name and If I use the below input.xml file with "name" element then I am getting default value for name field.

input.xml file:

So,how to set default value for missing element through jaxb?

By : Developer


The reason is your XML document are missing the elements. See the JAXB guide

When a class has an element property with the default value, and if the document you are reading is missing the element, then the unmarshaller does not fill the field with the default value. Instead, the unmarshaller fills in the field when the element is present but the content is missing

Try this input document

By : pedrofb

This video can help you solving your question :)
By: admin