如何使用jaxb读取属性?

时间:2013-08-14 13:16:28

标签: java spring jaxb xml-deserialization

鉴于此XML:

<response>
    <detail Id="123" Length="10" Width="20" Height="30" />
</response>

这就是我现在所拥有的,但它不起作用(我得到空的结果):

@XmlRootElement(name="response")
public class MyResponse {
    List<ResponseDetail> response;
    //+getters +setters +constructor
}

public class MyResponseDetail {
    Integer Id;
    Integer Length;
    Integer Width;
    Integer Height;
    //+getters +setters
}

我正在使用RestOperations拨打远程服务,我想解析<detail ..>元素。我已尝试将MyResponseMyResponseDetail类传递给RestOperations,但结果始终为空。

我的对象结构应该与该XML匹配?

1 个答案:

答案 0 :(得分:3)

你需要注释你的类:

@XmlRootElement
public class Response {

    private List<Detail> detail;

    public void setDetail(List<Detail> detail) {
        this.detail = detail;
    }
    public List<Detail> getDetail() {
        return detail;
    }

}

public class Detail {

    private String id;
    /* add other attributes here */

    @XmlAttribute(name = "Id")
    public void setId(String id) {
        this.id = id;
    }
    public String getId() {
        return id;
    }

}