Per gli attributi XML, il valore predefinito va all'interno del metodo getter.
per esempio,
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>
Si genererà classe come qui di seguito.
@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;
}
}
Creato XML di esempio per leggere
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Customer><element/></Customer>
quando scriviamo la logica per marshall nella nostra classe principale.
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());
Stampa in console. defaultElementName defaultAttributeValue
P.S -: per ottenere il valore di default di elementi hai bisogno di una copia in bianco di elemento in XML che viene marshalling.
fonte
2016-04-05 10:07:45
Cosa ... l'annotazione non ha effettivamente alcuna chiave defaultValue. Sono davvero piuttosto sorpreso. –
I valori predefiniti per gli elementi sono stati discussi [qui] (http://stackoverflow.com/questions/371127) - forse ti aiuterà per gli attributi. –