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());
- }