JAXB Annotations
29,738
Try this:
@XmlRootElement(name="car")
...
public class Car {
...
@XmlElementWrapper(name="recalls") // this name=... can be omitted, as it
// is the same as the field name
@XmlElement(name="recall")
private ArrayList<Recall> recalls;
}
From the documentation:
XmlElementWrapper: Generates a wrapper element around XML representation. This is primarily intended to be used to produce a wrapper XML element around collections.
Author by
mkluwe
Updated on July 09, 2022Comments
-
mkluwe almost 2 years
I need a little help with JAXB Annotations and I couldn't find good doc's helping me figure this out.
I have a class that I want to marshal into XML. My Class looks like this:
@XmlRootElement(name="car") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder = { "vid", "make", "model", "recalls", "engSpec" }) public class Car { @XmlElement(name="vid", required=true) private String vid; @XmlElement(name="make", required=true) private String make; @XmlElement(name="model", required=true) private String model; @XmlElement(name="recalls", required=true) private ArrayList<Recall> recalls; @XmlElement(name="engSpec", required=true) private EngSpec engSpec; ...
And the recall class looks like this:
@XmlRootElement(name = "recall") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder = { "type", "date" }) public class Recall { @XmlElement(name="type", required=true) private String type; @XmlElement(name="date", required=true) private String date; ...
So it produces this XML output:
<car> <vid>vid</vid> <make>make</make> <model>model</model> <recalls> <type>Recall1</type> <date>01/01/11</date> </recalls> <recalls> <type>Recall2</type> <date>01/01/11</date> </recalls> <engSpec> <power>200HP</power> <size>size</size> </engSpec> </car>
But what I want the ArrayList to display differently, like this:
<car> <vid>vid</vid> <make>make</make> <model>model</model> <recalls> <recall> <type>Recall1</type> <date>01/01/11</date> </recall> <recall> <type>Recall2</type> <date>01/01/11</date> </recall> </recalls> <engSpec> <power>200HP</power> <size>size</size> </engSpec> </car>
Any idea how I can do this? I think the problem is with my schema, but I use this for the marshalling:
JAXBContext jc = JAXBContext.newInstance(Car.class); Marshaller marsh = jc.createMarshaller(); marsh.marshal(car, out);
Any ideas how to fix this? Thanks!