「Java入門」XMLデータにバインドする方法を示すサンプルコード

1.Javaコード:
@XmlRootElement(name = “user”)
@XmlAccessorType(XmlAccessType.FIELD)
class User{
@XmlElement(name = “uname”)
private String username;
@XmlElement(name = “pword”)
private String password;
public User(String u,String p){
this.username = u;
this.password = p;
}
public User(){}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

@XmlRootElement(name = “team”)
@XmlAccessorType(XmlAccessType.FIELD)
class Team{
@XmlElementWrapper(name = “userList”)
@XmlElement(name = “user”)
private List<User> userList;
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}

public class JaxbTest {
public static void main(String[] args) throws Exception {
List<User> userList = new ArrayList<User>();
for(int i=0;i<2;i++){
userList.add(new User(“name”+i,”pword”+i));
}
Team team = new Team();
team.setUserList(userList);
JAXBContext context = JAXBContext.newInstance(User.class,Team.class);
Marshaller marshaller= context.createMarshaller();
marshaller.marshal(team, System.out);
}
}

2.出力結果:
<?xml version=”1.0″ encoding=”utf-8″?>

<team>
<userList>
<user>
<uname>name0</uname>
<pword>pword0</pword>
</user>
<user>
<uname>name1</uname>
<pword>pword1</pword>
</user>
</userList>
</team>