无法使用Jaxb从XML中提取值

时间:2017-10-02 05:49:29

标签: java xml jaxb

我正在尝试使用Jaxb从XML对象中提取其中一个对象。它不会返回任何错误日志。但是,它返回一个null对象。请找到代码。请告诉我只有Jaxb(不是用Documentbuilder方式)

XML字符串(ResponseXML)

 <DATAPACKET REQUEST-ID = "4">
 <HEADER>
     <RESPONSE-TYPE CODE = "0" DESCRIPTION = "Response Error" />
 </HEADER>
 <BODY>
     <ERROR-LIST>
        <ERROR-CODE>107</ERROR-CODE>
     </ERROR-LIST>
 </BODY>
 </DATAPACKET>

DataPacket

 @XmlAccessorType(XmlAccessType.NONE)
 @XmlRootElement(name = "DATAPACKET")
 public class DataPacket {    

 @XmlElement(name ="BODY")
 private Body BODY;

 public DataPacket (){}

 // Setter and getter of Body  

 }

身体

@XmlAccessorType(XmlAccessType.NONE)
public class Body{    

@XmlElement(name ="ERROR-LIST")
private ErrorListDto errorList;

 public Body(){}
 // Setter and getter of errorList
 }

ErrorListDto

 @XmlAccessorType(XmlAccessType.NONE)
 public class ErrorListDto{    

 @XmlElement(name="ERROR-CODE")
 private List<ErrorCodesDto> errorCodes;

 public ErrorListDto(){}

 // Setter and getter of errorCodes   
 }

ErrorCodesDto

@XmlAccessorType(XmlAccessType.NONE)
public class ErrorCodesDto {

@XmlElement(name = "ERROR-CODE")
private String ERROR_CODE;

public ErrorCodesDto() {}

我按如下方式提取值

JAXBContext jc = JAXBContext.newInstance(DataPacket.class);
 Unmarshaller unmarshaller = jc.createUnmarshaller();
 StringReader reader = new StringReader(responseXML);
 DataPacket dp = (DataPacket) unmarshaller.unmarshal(reader);                       
 Body body = dp.getBODY();
 ErrorListDto errorList = body.getErrorList();
 System.out.println(errorList.toString()); --> Here it has error code as null

请告诉我这里出了什么问题。任何想法都将不胜感激。

1 个答案:

答案 0 :(得分:2)

更改您的ErrorCodesDto,如下所示:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlValue;

@XmlAccessorType(XmlAccessType.NONE)
public class ErrorCodesDto {

    @XmlValue
    private String ERROR_CODE;

    public ErrorCodesDto() {
    }

}

否则你的预期&#34; xml&#34;应包含

 <ERROR-LIST>
        <ERROR-CODE><ERROR-CODE>107</ERROR-CODE></ERROR-CODE>
</ERROR-LIST>

要回答您的评论,该代码甚至可以使用以下xml

<DATAPACKET REQUEST-ID = "4">
 <HEADER>
     <RESPONSE-TYPE CODE = "0" DESCRIPTION = "Response Error" />
 </HEADER>
 <BODY>
     <ERROR-LIST>
        <ERROR-CODE>107</ERROR-CODE>
        <ERROR-CODE>108</ERROR-CODE>
        <ERROR-CODE>109</ERROR-CODE>
     </ERROR-LIST>
 </BODY>
 </DATAPACKET>
  

修改

您也可以在没有ErrorCodesDto课程的情况下实现这一目标,只需将ErrorListDto更改为

即可
@XmlElement(name = "ERROR-CODE") 
private List<String> errorCodes;