如何在JAXB中将Java集合转换为XMLElement的属性?

时间:2011-07-22 21:32:59

标签: java xml jaxb

我有以下2个班级。一个包含另一个数组..

@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;
  }
}

当我转换它时显示为

<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>

但我的要求是将其作为

<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>

1 个答案:

答案 0 :(得分:1)

CategoryDTO中,将@XmlElementWrapper替换为@XmlElement,即

@XmlElement(name="categoryleaf")
public CategoryLeafDTO[] getCategoryLeafDTO() {
    return this.categoryleafdto;
}
当您想要围绕您的集合的包装元素时,会使用

@XmlElementWrapper