How do I read attributes using jaxb?

旧城冷巷雨未停 提交于 2019-12-10 15:39:42

问题


Given this XML:

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

This is what I have now, but it is not working (I'm getting empty result):

@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
}

I'm making a call to a remote service using RestOperations and I want to parse the <detail ..> element. I've tried passing both MyResponse and MyResponseDetail classes to RestOperations but the result is always empty.

What should my object structure look like to match that XML?


回答1:


You need to annotate your classes like that:

@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;
    }

}


来源:https://stackoverflow.com/questions/18232795/how-do-i-read-attributes-using-jaxb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!