不确定标题是否有意义。 我有一个对象,我想使用看起来像这样的JAXB编组:
@XmlRootElement(name = "subscriptionRequest")
public class RegistrationRequest {
private Long id;
private RegistrationSource registrationSource;
}
RegistrationSource对象:
public class RegistrationSource {
private Integer id;
private String code;
}
我想创建一个具有以下布局的xml:
<subscriptionRequest registrationSource="0002">
...
</subscriptionRequest>
其中registrationSource属性值是RegistrationSource对象的代码字段值。
我需要使用哪些xml注释?
答案 0 :(得分:6)
@XmlAttribute
上的{p> registrationSource
,@XmlValue
上的code
。请注意,在这种情况下,您还应该@XmlTransient
的其他字段RegistrationSource
,例如id
编辑:这有效:
@XmlRootElement(name = "subscriptionRequest")
public class RegistrationRequest {
private Long id;
private RegistrationSource registrationSource;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
@XmlAttribute
public RegistrationSource getRegistrationSource() { return registrationSource; }
public void setRegistrationSource(RegistrationSource registrationSource)
{
this.registrationSource = registrationSource;
}
}
-
public class RegistrationSource {
private Integer id;
private String code;
@XmlTransient
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
@XmlValue
public String getCode() { return code; }
public void setCode(String code) { this.code = code; }
}
答案 1 :(得分:1)
如果您想使用某些工具自动生成此类,请尝试此操作 - 使用Trang之类的工具从xml生成xsd,然后使用jaxb从xsd生成java文件。生活会简单得多:)
答案 2 :(得分:0)
蹩脚的方法是添加像
这样的东西@XmlAttribute(name = "registrationSource")
private String getCode() {
return registrationSource.code;
}
到你的RegistrationSource
- 但必须有更优雅的方式......