在JAXB中需要一个元素或另一个元素 [英] require either one element or the other in JAXB
本文介绍了在JAXB中需要一个元素或另一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个JAXB注释的POJO如下:
I have a JAXB-annotated POJO like this:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Clazz implements Serializable {
@XmlElement(required = false)
private int a;
@XmlElement(required = false)
private int b;
}
我想标记该字段 a
或字段 b
是必需的。使用我当前的设置,它们都不是必需的,但我希望其中一个存在而不是另一个。我怎么能实现它?
I want to mark that either field a
or field b
is required. With my current set-up, none of them are required, but I want one of them to be present and not the other. How could I achieve it?
推荐答案
您可以使用 @XmlElementRefs $ c $执行以下操作c>
Clazz
import java.io.Serializable;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Clazz implements Serializable {
@XmlElementRefs({
@XmlElementRef(name="a", type=JAXBElement.class),
@XmlElementRef(name="b", type=JAXBElement.class)
})
private JAXBElement<Integer> aOrB;
}
ObjectFactory
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRegistry
public class ObjectFactory {
@XmlElementDecl(name = "a")
public JAXBElement<Integer> createA(Integer integer) {
return new JAXBElement<Integer>(new QName("a"), Integer.class, integer);
}
@XmlElementDecl(name = "b")
public JAXBElement<Integer> createB(Integer integer) {
return new JAXBElement<Integer>(new QName("b"), Integer.class, integer);
}
}
演示代码
演示
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Clazz.class, ObjectFactory.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum22502171/input.xml");
Clazz clazz = (Clazz) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(clazz, System.out);
}
}
input.xml /输出
<?xml version="1.0" encoding="UTF-8"?>
<clazz>
<b>123</b>
</clazz>
这篇关于在JAXB中需要一个元素或另一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文