JAXB 注释 [英] JAXB Annotations

查看:31
本文介绍了JAXB 注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 JAXB 注释方面的一些帮助,但找不到能帮助我解决这个问题的好文档.

I need a little help with JAXB Annotations and I couldn't find good doc's helping me figure this out.

我有一个类要编组到 XML 中.我的班级看起来像这样:

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

召回类看起来像这样:

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

所以它产生这个 XML 输出:

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>

但是我希望 ArrayList 以不同的方式显示,如下所示:

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!

推荐答案

试试这个:

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

来自文档:

XmlElementWrapper:围绕 XML 表示生成包装元素.这主要用于围绕集合生成包装器 XML 元素.

XmlElementWrapper: Generates a wrapper element around XML representation. This is primarily intended to be used to produce a wrapper XML element around collections.

这篇关于JAXB 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆