跟随xml的jaxb注释

时间:2016-08-30 11:06:13

标签: java xml jaxb

我读到了JAXB,我是新手。我想从我的类

中跟随xml
<response>
  <command></command>
  <message></message>
</response>

这是我的课程

抽象父类 - 响应

@XmlRootElement
abstract class Response {
String command;

public Response() {
    // TODO Auto-generated constructor stub
}

public Response(String command) {
    this.command = command;
}

@XmlElement
public String getCommand() {
    return command;
}

public void setCommand(String command) {
    this.command = command;
}
}

子类:MessageResposne

@XmlRootElement
class MessageResponse extends Response {
String message;

public MessageResponse() {
    // TODO Auto-generated constructor stub
}

public MessageResponse(String command, String message) {
    super(command);
    this.message = message;
}

@XmlElement
public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

}

并在主要班级

try {
      objContext = JAXBContext.newInstance(Response.class);
      objMarshaller = objContext.createMarshaller();
    } catch (JAXBException e) {
       e.printStackTrace();
      }

但这是产生

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><response><command>setname</command></response>

我需要对所需的resposne做什么操作

1 个答案:

答案 0 :(得分:1)

@XmlSeeAlso会有帮助吗?

@XmlRootElement
@XmlSeeAlso({MessageResponse.class})
abstract class Response {
  String command;

  public Response() {
    // TODO Auto-generated constructor stub
  }

  public Response(String command) {
    this.command = command;
  }

  @XmlElement
  public String getCommand() {
    return command;
  }

  public void setCommand(String command) {
    this.command = command;
  }
}

它告诉JAXB在绑定MessageReponse时绑定Response

此外,通过将 MessageResponse.java 的第一行更改为:

MessageResponse类必须与response元素名称相关联。
@XmlRootElement(name="response")

我可以使用以下Main类重现所需的输出:

package test;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main{
  public static void main(String[] args)
  {
    try {
      JAXBContext objContext = JAXBContext.newInstance(Response.class);
      Marshaller objMarshaller = objContext.createMarshaller();
      objMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      MessageResponse mr = new MessageResponse("", "");
      objMarshaller.marshal(mr, System.out);
    } catch (JAXBException e) {
       e.printStackTrace();
    }
  }
}