سؤال

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;
}

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?

هل كانت مفيدة؟

المحلول

You can do the following with @XmlElementRefs

Domain Model

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);
    }

}

Demo Code

Demo

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/Output

<?xml version="1.0" encoding="UTF-8"?>
<clazz>
    <b>123</b>
</clazz>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top