在JAXB中需要一个元素或另一个元素

时间:2014-03-19 10:00:54

标签: java jaxb xml-serialization xml-deserialization

我有一个带有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。使用我当前的设置,它们都不是必需的,但我希望其中一个存在而不是另一个。我怎么能实现它?

1 个答案:

答案 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>