JAXB dynamic XML root class name

563 views Asked by At

I have my User class in java. When I want to unmarshal it, I get xml with <UserIn> root element, and when I want to marshal it I should do <UserOut> to be XML root element. If I provide @XmlRootElement("UserIn") it is not dynamic and it is always UserIn root. Is there any way to do dynamic root element on class? thanks.

1

There are 1 answers

1
martidis On

You could create two classes that extend your User class, and then use the specific child class based on if you are marshalling on unmarshalling.

For example, for a class User:

public class User {

    @XmlElement
    private String value;

    public User() { }

    public User(String value) {
        this.value = value;
    }
}

You can have UserIn:

@XmlRootElement(name = "UserIn")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserIn extends User {

    public UserIn() { }

    public UserIn(String value) {
        super(value);
    }
}

and UserOut:

@XmlRootElement(name = "UserOut")
@XmlAccessorType(XmlAccessType.FIELD)
public class UserOut extends User {

    public UserOut() { }

    public UserOut(String value) {
        super(value);
    }
}

Provide the appropriate class where you need, and you will get it working with the input or output you wish.