我有下面提到的xml字符串和Team类。我想使用jaxb将所有行元素转换为团队列表。
<team-all>
<query-output>
<row teamId="1" teamName ="MyTeam1" />
<row teamId="2" teamName ="MyTeam2" />
</query-output>
</team-all>
public class Team {
private String teamId;
private String teamName;
public String getTeamId() {
return teamId;
}
public void setTeamId(String teamId) {
this.teamId = teamId;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
}
答案 0 :(得分:0)
@XmlRootElement(name="team-all")
@XmlAccessorType(XmlAccessType.FIELD)
public class AllTeam{
@XmlElementWrapper(name="query-output")
@XmlElement(name="row")
private List<Team> teams;
//getters and setters
}
@XmlAccessorType(XmlAccessType.FIELD)
public class Team {
@XmlAttribute
private String teamId;
@XmlAttribute
private String teamName;
public String getTeamId() {
return teamId;
}
public void setTeamId(String teamId) {
this.teamId = teamId;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
}
然后
Unmarshaller um = JAXBContext.newInstance(AllTeam.class).createUnmarshaller();
AllTeam tm = um.unmarshall(new File("pathToXml"));
如果文件不适合你,unmarshall方法可以接受不同的输入。