public class XmlToBean {
public static void main(String[] args) {
// User user = new User(20, "小明明");
// user.setName("小红");
User user = new User();
user.setName("小黄");
try {
System.out.println("bean转xml字符串");
String s = XmlUtil.beanToXmlStr(user);
System.out.println(s);
System.out.println("xml转字符串");
User userTemp = XmlUtil.xmlToBean(s, User.class);
System.out.println(userTemp);
} catch (JAXBException e) {
e.printStackTrace();
}
}
static class XmlUtil{
//xml转baen实体
public static <T> T xmlToBean(String xmlStr,Class<T> load) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(load);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
T unmarshal = (T)unmarshaller.unmarshal(new StringReader(xmlStr));
return unmarshal;
}
//bean转xml
public static String beanToXmlStr(Object bean) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(bean.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
StringWriter stringWriter = new StringWriter();
marshaller.marshal(bean,stringWriter);
return stringWriter.toString();
}
}
@XmlRootElement
static class User{
Integer age;
String name;
public User(){
}
public User(Integer age, String name) {
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
}