Java bean 转为xml可以采用XStream类来完成

pom.xml

<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.9</version>
</dependency>

public class BaseMessage {
  @XStreamAliasC"ToUserName")
  private String toUserName;
  @XStreamAlias(" FromUserName")
  private String fromUserName ;
  @XStreamAliasC"CreateTime")
  private String createTime ;
  @XStreamAliasC"MsgType")
  private String msgType;

       get.set...

}

 

@XStreamAlias("xml")
public class TextMessage extends BaseMessage {
  @XStreamAliasC"Content")
  private String content;

      get.set...

}

测试代码:

XStream stream = new XStream();
//
stream. processAnnotations(TextMessage. class);
String xml = stream. toXML(tm); //tm是TextMessage类对象
System. out. println(xml );

 

 输出结果:

<xml>
  <ToUserName>from</ToUserName>
  <FromUserName>to</FromUserName>
  <CreateTime>1540898036</CreateTime>
  <MsgType>text </MsgType>
  <Content>还好</Content>
</xml>