类文件注解:@XmlRootElement不可缺少
@XmlRootElement
public class Man {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Java 转换 Xml:
@Test
public void testJava2Xml(){
try {
JAXBContext jc = JAXBContext.newInstance(Man.class);
Marshaller ms = jc.createMarshaller();
Man man = new Man("man",100);
ms.marshal(man, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
Xml 转换 Java:
@Test
public void testXml2Java() throws JAXBException{
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Man><age>100</age><name>man</name></Man>";
JAXBContext jc = JAXBContext.newInstance(Man.class);
Unmarshaller unmar = jc.createUnmarshaller();
Man man = (Man) unmar.unmarshal(new StringReader(xml));
System.out.println(man.getName());
}
感谢阅读,如果感觉可以评论点赞!!!!