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

标签 java xml jaxb

我有以下两门类(class)。一个包含另一个的数组..

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

最佳答案

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

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

@XmlElementWrapper 在您想要围绕集合的包装元素时使用。

关于java - 如何将Java集合转换为JAXB中XMLElement的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6796363/

相关文章:

java - JBoss 类加载器存储库

java - 如何将 Javadoc 目录添加到 Wordpress 站点

android - 布局土地不起作用?

java - 当有静态类时,没有带有 @XmlElementDecl 的 ObjectFactory

java - 如何解决错误 'nexpected element (uri:"“,本地 :"Create"”。预期元素是 <{}Create>'?

java - JAXB/Jackson XML 通用序列化

java - FileOutputStream: "close"方法是否也调用 "flush"?

java - 如何让用户在读取csv文件时出现一次?

xml - 将 xml 解码为结构

java - JAXB 解码返回 'URI is not absolute' 错误