pro_newbie
pro_newbie

Reputation: 336

Java How to add child elements in XML using JAXB annotations

I have been trying to create following XML by using JAXB Annotations.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Response>
    <resultCode>00</resultCode>
    <resultDesc>Success</resultDesc>
    <SenderResponse>
        <match>false</match>
        <code>02</code>
    </SenderResponse>
    <ReceiverResponse>
        <match>true</match>
        <code>00</code>
    </ReceiverResponse>
</Response>

So far I am able to achieve following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Response>
    <resultCode>02</resultCode>
    <resultDesc>Telenor Mismatched</resultDesc>
</Response>

I have searched but could not find how can I add child elements in the above mentioned XLM by using following Java code.

@XmlRootElement(name = "Response")
public class Response 
{
    String ResultCode;
    String ResultDesc;

    @XmlElement
    public String getResultCode() {
        return ResultCode;
    }
    public void setResultCode(String resultCode) {
        ResultCode = resultCode;
    }

    @XmlElement
    public String getResultDesc() {
        return ResultDesc;
    }
    public void setResultDesc(String resultDesc) {
        ResultDesc = resultDesc;
    }
}

I am calling above class by simply doing.

Response response = new Response();
response.setResultCode("22");
response.setResultDesc("error");

Upvotes: 0

Views: 1125

Answers (1)

Joe
Joe

Reputation: 800

You are on the right track. What you will want to do for nested elements is to create new classes to mirror them. Create a SenderResponse class, then use it like this:

@XmlElement
public SenderResponse getSenderResponse() {
}

EDIT: Then inside the SenderResponse class you will have the sub elements.

@XmlElement
public String getMatch() {
}

@XmlElement
public String getCode() {
}

Upvotes: 1

Related Questions