有一个像这样的简单代码:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class A {
@XmlPath("B/text()")
private String b;
@XmlPath("C/text()")
private Integer c;
...
}
只要我的 XML 中有合适的值,它就绝对可以正常工作。我想将字段 c
标记为必需,因此每次我尝试读取 c
未设置或无效的文档时,MOXy 都会抛出异常。最简单的解决方案是什么?
更新:
设置默认值也可以。
最佳答案
EclipseLink JAXB (MOXy)或者任何 JAXB 实现都不会对丢失的节点执行设置操作,因此您可以执行以下操作:
选项 #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
上指定 defaultValue
您可以在@XmlElement
注释上指定defaultValue,但这只会在解码空元素时设置defaultValue。
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 架构以强制验证
使用 MOXy 或任何 JAXB 实现,您可以在 Unmarshaller 上设置 XML 模式以验证输入:
关于java - 使用 MOXy 读取 XML 时如何将字段标记为必填/可选?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7192619/