Marching an object with object fields

Not sure if the name makes sense. I have an object that I want to make using JAXB, which looks like this:

@XmlRootElement(name = "subscriptionRequest")
    public class RegistrationRequest {

    private Long id;
    private RegistrationSource registrationSource;
    }

RegistrationSource Object:

 public class RegistrationSource {

    private Integer id;
    private String code;
}

I want to create an xml that has the following layout:

<subscriptionRequest registrationSource="0002">
    ...
</subscriptionRequest>

where the value of the registrationSource attribute is the value of the code field from the RegistrationSource object.

What XML annotations do I need to use?

+3
source share
3 answers

@XmlAttributeon registrationSource, @XmlValueon code. Please note that in this case you should also have @XmlTransientin other fields registrationSource, for exampleid

EDIT: This works:

@XmlRootElement(name = "subscriptionRequest") 
public class RegistrationRequest { 

    private Long id; 
    private RegistrationSource registrationSource; 

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    @XmlAttribute
    public RegistrationSource getRegistrationSource() { return registrationSource; }
    public void setRegistrationSource(RegistrationSource registrationSource)
    {
        this.registrationSource = registrationSource;
    }
}

-

public class RegistrationSource { 

    private Integer id; 
    private String code; 

    @XmlTransient
    public Integer getId() { return id; }
    public void setId(Integer id) { this.id = id; }

    @XmlValue
    public String getCode() { return code; }
    public void setCode(String code) { this.code = code; }
}
+6
source

, - xsd xml , Trang, java xsd jaxb. :)

+1

A weak approach would be to add something like

@XmlAttribute(name = "registrationSource")
private String getCode() {
    return registrationSource.code;
}

to yours RegistrationSource- but there should be a more elegant way ...

0
source

Source: https://habr.com/ru/post/1729387/


All Articles