用于接口接收到的是xml报文,需转成bean处理。待处理完逻辑,把相应的bean再转成xml报文
//bean
@lombok
@XmlAccessorType(XmlAccessType.FIELD)
public class Head {
private String fromId;
private String systemId;
public Head(String fromId, String systemId) {
this.fromId = fromId;
this.systemId = systemId;
}
}
@lombok
@XmlAccessorType(XmlAccessType.FIELD)
public class Body {
private String code;
private String msg;
public Body(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
@lombok
@XmlRootElement(name = "service")
@XmlAccessorType(XmlAccessType.FIELD)
public class Bean {
@XmlElement(name="head")
private Head head;
@XmlElement(name="body")
private Body body;
public Bean(Head head, Body body) {
this.head = head;
this.body = body;
}
}
//监听器 实体属性为null则转为""生成标签
class MarshallerListener extends Marshaller.Listener{
public static final String BLANK_CHAR = "";
@Override
public void beforeMarshal(Object source) {
super.beforeMarshal(source);
Field[] fields = source.getClass().getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
try {
if ((f.getType() == String.class||f.getType() ==Integer.class||f.getType()==Double.class||f.getType()== List.class)&& f.get(source) == null) {
f.set(source, BLANK_CHAR);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
//测试
public class Test {
public static void main(String[] args) throws JAXBException {
System.out.println("==========bean转xml===========");
Head head = new Head("xt1","xitong1");
Body body = new Body("000020","成功");
Bean bean = new Bean(head,body);
JAXBContext context = JAXBContext.newInstance(Bean.class);
Marshaller marshaller = context.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.setListener(new MarshallerListener());//如属性为null,不需要转成标签,则省略此行代码
marshaller.marshal(bean,stringWriter);
String xml = stringWriter.toString();
System.out.println("xml:"+xml );
System.out.println("==========xml转bean===========");
Unmarshaller unmarshaller = context.createUnmarshaller();
Bean bean = (Bean)unmarshaller.unmarshal(new StringReader(xml));
Head head = bean.getHead();Body body = bean.getBody();
}
}