Search code examples
javamarshallingunmarshallingjaxb2

JAXB wrap all fields


Currently I have a simple class setup as:

@XmlRootElement (name = "MyRoot")
public class MyClass {

  @XmlElement (name = "String1") private String string1;
  @XmlTransient public String getString1() { return this.string1; }
  public void setString1(String string1) { this.string1 = string1; }

  @XmlElement (name = "String2") private String string2;
  @XmlTransient public String getString2() { return this.string2; }
  public void setString2(String string2) { this.string2 = string2; }
}

I want the output of the class when processed from JAXB to look like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<MyRoot>
  <MyWrapper>
    <String1>ABC</String1>
    <String2>XYZ</String2>
  </MyWrapper>
</MyRoot>

My questions are:

  1. Is there any way to do this without creating an inner class that is setup with @XmlRootElement(name = "MyWrapper" on it? Is this a simple limitation of JAXB?
  2. Is this a limitation of JAXB?
  3. Is is possible to write/implementation a custom marshaling and unmarshalling object of some type to deal with this type of a scenario?

Solution

  • How is this a limitation, clearly String1 and String2 are members of MyClass, and unless you redefine their parents, its not just going to change like that.

    Suggestion, make them transient, use method annotation, and return an array of both of them