使用MOXy读取XML时,如何将字段标记为必填/可选? [英] How do I mark fields as required/optional when reading XML with MOXy?
问题描述
具有这样的简单代码:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
@XmlPath("B/text()")
private String b;
@XmlPath("C/text()")
private Integer c;
...
}
只要我在XML中具有apt值,它就可以正常工作.我想根据需要标记 c
字段,所以每次尝试读取未设置 c
或无效的文档时,MOXy都会抛出该异常.最简单的解决方案是什么?
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?
更新:
设置默认值也可以.
推荐答案
EclipseLink JAXB(MOXy)或任何JAXB实现都不会对丢失的节点执行设置操作,因此您可以执行以下操作:
EclipseLink JAXB (MOXy) or any JAXB implementation will not perform a set operation for missing nodes, so you could do the following:
选项1-默认字段值
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;
}
具有以下演示代码:
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());
}
}
将产生以下输出:
fieldDefault
null
选项#2-在 @XmlElement
Option #2 - Specify defaultValue on @XmlElement
您可以在 @XmlElement
批注上指定defaultValue,但这仅在解组空元素时才设置defaultValue.
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;
}
带有以下演示代码:
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());
}
}
将产生以下输出:
annotationDefault
null
选项#3-在 Unmarshaller
上指定XML模式以强制进行验证
Option #3 - Specify an XML schema on the Unmarshaller
to force validation
使用MOXy或任何JAXB实现,您可以在Unmarshaller上设置XML模式以验证输入:
Using MOXy or any JAXB implementation you can set an XML schema on the Unmarshaller to have the input validated:
这篇关于使用MOXy读取XML时,如何将字段标记为必填/可选?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!