我有一个带有JAXB注释的POJO:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Clazz implements Serializable {
@XmlElement(required = false)
private int a;
@XmlElement(required = false)
private int b;
}
我想标记要求字段a
或字段b
。使用我当前的设置,它们都不是必需的,但我希望其中一个存在而不是另一个。我怎么能实现它?
答案 0 :(得分:2)
您可以使用@XmlElementRefs
<强> 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>