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

Question!

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="http://www.w3.org/2001/XMLSchema">

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

</xs:schema> 

2. Customer.model

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "name",
    "phoneNumber"
})
@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) {
        this.name = value;
    }
    public BigInteger getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(BigInteger value) {
        this.phoneNumber = value;
    }
}

3. input.xml

<customer>

</customer>

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();
unmarshaller.setSchema(schema);
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:
<customer><name/></customer>

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

By : Developer


Answers

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