简体   繁体   中英

How to transform a Java collection to attributes of XMLElement in JAXB?

I have the following 2 classes. One contains an array of the other..

@XmlType(name="category", propOrder =          { "title", "description", "sdImg", "hdImg","categoryLeafDTO" } ) 
public class CategoryDTO implements Serializable {
    @XmlElementWrapper (name="categoryleaf")
    public CategoryLeafDTO[] getCategoryLeafDTO() {
        return this.categoryleafdto;
    }

    public void setCategoryLeafDTO(CategoryLeafDTO[] categoryleafdto) {
       this.categoryleafdto = categoryleafdto;
    }
}

@XmlType (name = "categoryleaf" , propOrder = { "title", "description", "autoplay" }) 
public class CategoryLeafDTO implements Serializable {
  private static final long serialVersionUID = 1L;
  private String title;
  private String description;
  private String autoplay;

  @XmlAttribute (name="title")
  public String getTitle() {
     return title;
  }

  public void setTitle(String title) {
     this.title = title;
  }

  @XmlAttribute (name="description")
  public String getDescription() {
     return description;
  }

  public void setDescription(String description) {
     this.description = description;
  }

  @XmlAttribute (name="autoplay")
  public String getAutoplay() {
     return this.autoplay;      
  }

  public void setAutoplay(String autoplay) {
     this.autoplay = autoplay;
  }
}

When I transform it shows up as

<category title="Trailers" description="Just Trailers"     sd_img="http://a.dolimg.com/media/en-US/m/dcom/tvapp/roku/assets/trailers_v4e_250.png"    hd_img="http://a.dolimg.com/media/en-US/m/dcom/tvapp/roku/assets/trailers_v4e_250.png">
   <categoryleaf>
      <categoryLeafDTO title="Trailers" description="Just Trailers" autoplay="ON" /> 
      <categoryLeafDTO title="Cars" description="cars the movie" autoplay="OFF" /> 
   </categoryleaf>
</category>

But my requirements is to have it as

<category title="Trailers" description="Just Trailers"  sd_img="http://a.dolimg.com/media/en-US/m/dcom/tvapp/roku/assets/trailers_v4e_250.png"  hd_img="http://a.dolimg.com/media/en-US/m/dcom/tvapp/roku/assets/trailers_v4e_250.png">
   <categoryleaf title="Trailers" description="Just Trailers" autoplay="ON">
   <categoryleaf title="Cars" description="cars the movie" autoplay="OFF">
</category>

In CategoryDTO , replace @XmlElementWrapper with @XmlElement , ie

@XmlElement(name="categoryleaf")
public CategoryLeafDTO[] getCategoryLeafDTO() {
    return this.categoryleafdto;
}

@XmlElementWrapper is used when you want a wrapper element surrounding your collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM