JAXBで一要素に属性と値を設定する際のメモです。
例題として、下記GracenoteのAPIページ「楽曲の詳細属性を検索」欄のTEXT要素を表現するを取り上げます。
設定方法は、該当要素のオブジェクトで値を設定するgetterに「@XmlValue」のアノテーションを付与します。
MusicQueryBean.java
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/*
*QUERY配下の要素を設定するオブジェクト
*/
public class MusicQueryBean{
public MusicQueryBean() {}
private String cmd;
private String mode;
private List<TextParamBean> textParamList;
private List<OptionParamBean> optionParamList;
@XmlAttribute(name="CMD")
public String getCmd() {
return this.cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
@XmlElement(name="MODE")
public String getMode() {
return this.mode;
}
public void setMode(String mode) {
this.mode = mode;
}
// 該当の要素を設定するリスト
@XmlElement(name="TEXT")
public List<TextParamBean> getTextParamList() {
return this.textParamList;
}
public void setTextParamList(List<TextParamBean> textParamList) {
this.textParamList = textParamList;
}
@XmlElement(name="OPTION")
public List<OptionParamBean> getOptionParamList() {
return this.optionParamList;
}
public void setOptionParamList(List<OptionParamBean> optionParamList) {
this.optionParamList = optionParamList;
}
}
TextParamBean.java
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
/*
*TEXT要素を設定するオブジェクト
*/
public class TextParamBean{
public TextParamBean() {}
private String text;
private String type;
@XmlAttribute(name="TYPE")
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
@XmlValue
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
}
参考
java - XML element with attribute and content using JAXB - Stack Overflow
Java - JAXB使い方メモ - Qiita