java和xml的互相转换,依靠强大的JAXBContext可以轻松实现。
下面通过一个简单案例学习一下JAXBContext
首先准备好一个JavaBean供实验:
注意
1、类文件注解:@XmlRootElement不可缺少
2、2个Student的构造方法不能少
@XmlRootElement public class Student { private String name; private String width; private String height; private int age; public Student(String name,String width,String height,int age) { super(); this.name = name; this.width = width; this.height = height; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Student() { super(); } }
JavaToXml:
@Test public void test01(){ try { JAXBContext jc = JAXBContext.newInstance(Student.class); Marshaller ms = jc.createMarshaller(); Student st = new Student("zhang","w","h",11); ms.marshal(st,System.out); } catch (JAXBException e) { // Todo Auto-generated catch block e.printstacktrace(); } }
XmlToJava
//xml转换Java @Test public void test02() throws JAXBException{ String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>11</age><height>h</height><name>zhang</name><width>w</width></student>"; JAXBContext jc = JAXBContext.newInstance(Student.class); Unmarshaller unmar = jc.createUnmarshaller(); Student stu = (Student) unmar.unmarshal(new StringReader(xml)); System.out.println(stu.getName()); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。