使用 jaxB 解组 xml 时获取空值

Getting getting null values when unmarshalling the xml using jaxB

这是我的豆子class

class resp {
  String code;
  String msg;
  resp() {
    code = null;
    msg = null;
  }
  resp(String code, String msg) {
    this.code = code;
    this.msg = msg;
  }
  @XmlAttribute(name = "code")
  public String getCode() {
    return code;
  }
  public void setCode(String code) {
    this.code = code;
  }
  @XmlAttribute(name = "msg")
  public String getMsg() {
    return msg;
  }
  public void setMsg(String msg) {
    this.msg = msg;
  }
}

此 class 包含响应列表 class

@XmlRootElement(name = "resps")
class resps {

  List<resp> resp = null;

  @XmlElement
  public List<resp> getResp() {
    return resp;
  }
  public void setResp(List<resp> resp) {
    this.resp = resp;
  }
}

主要方法:我在其中使用 jaxb 将 resps.xml 解组为 java 对象 (resps)

public static void main(String args[]) throws JAXBException {
    try {
        File file = new File("resps.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(resps.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        resps res = (resps) jaxbUnmarshaller.unmarshal(file);

        List<resp> list = res.getResp();
        int i = 1;
        for (resp ans : list){
            System.out.println(" record " + i++ + " contents :" + ans.code
                    + " " + ans.msg);
        }

    } catch (JAXBException e) {
        e.printStackTrace();
    }
}

----------------------------resps.xml------------ ----------------------

<?xml version="1.0" encoding="UTF-8"?>
<resps> 
  <resp>
  <code>testCode1</code>
  <msg>testMsg1</msg>           
  </resp>
<resp>
<code>testCode2</code>
<msg>testMsg2</msg>         
</resp>

</resps>

输出

在您的 resp.class 中,您使用 @XmlAttribute 注释代码和消息 getter 方法,但在您的 xml 中,它们作为元素存在。将注释 @XmlAttribute 更改为 @XmlElement.

class resp {
    String code;
    String msg;

    resp() {
        code = null;
        msg = null;
    }

    resp(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @XmlElement(name = "code")
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @XmlElement(name = "msg")
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

如果您的 xml 如下所示,请使用 @XmlAttribute:

<?xml version="1.0" encoding="UTF-8"?>
<resps>
    <resp code="testCode1" msg = "testMsg1"/>
    <resp code="testCode2" msg = "testMsg2"/>
</resps>

更改您的 resp.java 代码,如下所示

@XmlElement(name = "code")
public String getCode()
{
    return code;
}


@XmlElement(name = "msg")
public String getMsg()
{
    return msg;
}

我建议你应该参考一些教程,关于什么是 XmlAttribute and XmlElement