Search code examples
javaxmljaxb2

@XMLRootElement element or array name


I am currently trying to unmarshall a xml get response into one intricate java object. That java object has other classes as fields, so it goes very deep. Now, I am using the JaxbMarshaller2 for this job. So far everything has been going well, but now I am have a question:

Basically one of the tags in the XML stream is called "images" and contains an array of individual image items, each enclosed in the "item" tag.

<images>
   <item>
      <name></name>
   </item>
   <item>
      <name></name>
   </item>
</images>

Now, in my root java class, I have a property called images, which is a list of these image items (I made a custom class for these items.)

@XmlElement(name = "images")
private List<ProductImage> images;

Ok, now inside the ProductImage class, would the XML root element above the class name be @XmlRootElement(name="images") or @XmlRootElement(name="item")?

Thanks for your responses.


Solution

  • The @XmlRootElement annotation is only necessary for the root element of your xml file. Each parent always defines the names of the tags of its children. But since the root element has no parent, there is an additional annotation necessary to define its name (i.e. @XmlRootElement).

    Option1:

    Assuming that the <images> node is your root node of your xml file. Create a class ProductImageCollection which has the @XmlRootElement(name="images") annotation.

    Inside this class there should be a List<ProductImage> which has an annotation @XmlElement(name="image")

    Option2:

    Assuming that your <images> node is part of a bigger xml structure, which already has correct annotations.

    Then you don't need any additional @XmlRootElement annotations. You can directly annotate your list with @XmlElementWrapper(name="images").