Wrap XML elements in a sub-element with JAXB/JAX-RS

Viewed 103

I have the following class which shall be serialized/deserialized to XML.

@XmlRootElement(name = "nnxml")
@XmlAccessorType(XmlAccessType.FIELD)
public class InfoRequest {

    @XmlElement(name = "vendor_id")
    private String vendorId;

    @XmlElement(name = "vendor_authcode")
    private String authCode;
}

This currently gives me this XML which is consistent and correct:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nnxml>
    <vendor_id>vendor id</vendor_id>
    <vendor_authcode>auth code</vendor_authcode>
</nnxml>

However I need to wrap the XML elements in another element like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nnxml>
  <info_request>
      <vendor_id>vendor id</vendor_id>
      <vendor_authcode>auth code</vendor_authcode>
  </info_request>
</nnxml>

How can I wrap the above fields in a info_request element? Do I have to create something like an inner class or is there a simpler approach?

1 Answers

One approach is to create a Wrapper class like this and to insert your class

@XmlRootElement(name = "nnxml")
@XmlAccessorType(XmlAccessType.FIELD)
public class Nnxml implements Serializable {

    @XmlElement(name = "info_request")
    private InfoRequest request;
}

The annotations of subclass are optional

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "info_request", propOrder = {
        "vendorId",
        "authCode"
})
class InfoRequest implements Serializable{
    @XmlElement(name = "vendor_id")
    private String vendorId;

    @XmlElement(name = "vendor_authcode")
    private String authCode;
}

Output is

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<nnxml>
    <info_request>
        <vendor_id>vendor id</vendor_id>
        <vendor_authcode>auth code</vendor_authcode>
    </info_request>
</nnxml>
Related