1.写一个工具类:
public static String convertToXml(Object obj, String encoding) {
String result = null;
try {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
StringWriter writer = new StringWriter();
marshaller.marshal(obj, writer);
result=writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
2.创建三个bean
2.1.Student作为根节点,用到的注解如下:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
@XmlType(propOrder = {})
public class Student {
@XmlElement(name="head")
private Head head;
@XmlElement(name = "body")
private Body body;
2.2Head、Body作为根节点的子节点
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder = { "name", "desc" })
public class Body {
@XmlElement
private String name;
@XmlElement
private String desc;
3.测试一下:
Student student = new Student();
Body body = new Body();
Head head=new Head();
head.setDesc("1");
head.setName("111");
body.setDesc("2");
body.setName("222");
student.setBody(body);
student.setHead(head);
String str = JaxbUtil.convertToXml(student,"GBK");
System.out.println(str);
这样基本实现javaBean转成xml。
4.xml字符串转成javaBean,一个方法足以。
public static T converyToJavaBean(String xml, Class c) {
T t = null;
try {
JAXBContext context = JAXBContext.newInstance(c);
Unmarshaller unmarshaller = context.createUnmarshaller();
t = (T) unmarshaller.unmarshal(new StringReader(xml));
} catch (Exception e) {
e.printStackTrace();
}
return t;
}