For XML attributes, the default value is included in the getter method.
for example,
customer.xsd
<?xml version="1.0" encoding="UTF-8"?> <schema xmlns="http://www.w3.org/2001/XMLSchema"> <element name="Customer"> <complexType> <sequence> <element name="element" type="string" maxOccurs="1" minOccurs="0" default="defaultElementName"></element> </sequence> <attribute name="attribute" type="string" default="defaultAttributeValue"></attribute> </complexType> </element> </schema>
It will generate a class as shown below.
@XmlRootElement(name = "Customer") public class Customer { @XmlElement(required = true, defaultValue = "defaultElementName") protected String element; @XmlAttribute(name = "attribute") protected String attribute; ...... public String getAttribute() {
Read XML Sample Created
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customer><element/></Customer>
when we write the logic for the marshall in our main class.
File file = new File("...src/com/testdefault/xsd/CustomerRead.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file); System.out.println(customer.getElement()); System.out.println(customer.getAttribute());
It will print on the console. defaultElementName defaultAttributeValue
PS -: to get the default value for elements you need to have an empty copy of the element in xml, which is sorted.
Kumar abhishek
source share