JAXB default attribute value

I use JAXB annotations to generate the xsd schema from my classes.

Annotation @XmlElement with the defaultValue parameter sets the default value for the element. Can I set a default value for @XmlAttribute?

PS I checked that the xsd syntax allows you to set default values ​​for attributes

+8
java xml xsd jaxb
source share
3 answers

Could check this: Does JAXB support default schema values?

To be honest, I have no clue why there is no default option for an attribute in standard JAXB.

+3
source share

When you create classes from xsd, where you define an attribute with a default value, then jaxb will generate an if clause, where it will check for a null value, and if so, will return the default value.

0
source share

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() { //here the default value is set. if (attribute == null) { return "defaultAttributeValue"; } else { return attribute; } } 

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.

0
source share

All Articles