如何使用具有不同root和child元素的jaxb将xml字符串转换为java对象列表

时间:2016-06-08 17:15:14

标签: java jaxb

我有下面提到的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;
}
}

1 个答案:

答案 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方法可以接受不同的输入。