有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用jaxb读取属性?

鉴于此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) 个答案

  1. # 1 楼答案

    您需要这样注释您的类:

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