How do I mark fields as required/optional when reading XML with MOXy?
Having a trivial c开发者_JS百科ode like this:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
@XmlPath("B/text()")
private String b;
@XmlPath("C/text()")
private Integer c;
...
}
It works absolutely fine as long as I have apt values in my XML. I'd like to mark the field c
as required, so MOXy throw every time I try to read the document where c
is either not set, or invalid. What's the easiest solution?
Update:
Setting default values will also do.
EclipseLink JAXB (MOXy) or any JAXB implementation will not perform a set operation for missing nodes, so you could do the following:
Option #1 - Default the field value
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
@XmlPath("B/text()")
private String b = "fieldDefault";
@XmlPath("C/text()")
private Integer c;
}
With the following demo code:
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
A a = (A) unmarshaller.unmarshal(new StringReader("<a/>"));
System.out.println(a.getB());
System.out.println(a.getC());
}
}
Will produce the following output:
fieldDefault
null
Option #2 - Specify defaultValue on @XmlElement
You can specify a defaultValue on the @XmlElement
annotation, but this will only set the defaultValue when an empty element is unmarshalled.
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
@XmlPath("B/text()")
@XmlElement(defaultValue="annotationDefault")
private String b;
@XmlPath("C/text()")
@XmlElement(defaultValue="annotationDefault")
private Integer c;
}
With the following demo code:
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
A a = (A) unmarshaller.unmarshal(new StringReader("<a><B/></a>"));
System.out.println(a.getB());
System.out.println(a.getC());
}
}
Will produce the following output:
annotationDefault
null
Option #3 - Specify an XML schema on the Unmarshaller
to force validation
Using MOXy or any JAXB implementation you can set an XML schema on the Unmarshaller to have the input validated:
- http://blog.bdoughan.com/2010/12/jaxb-and-marshalunmarshal-schema.html
精彩评论