我如何使用JAXB读取属性?

4

考虑以下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个回答

4
您需要这样注释您的类:
@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;
    }

}

+1 - 编辑了你的答案,修复了Response类上的访问器,并删除了不必要的注释。 - bdoughan
1
感谢你对我的回答进行了改进! - Benoit Wickramarachi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接