XML 施用JAXB创建xml java解析xml

XML 使用JAXB创建xml java解析xml

下面我们通过两个bean类创建和解析xml文件

package com.sg.xml;

public class ClassRoom {
 private int id ;
 private String name;
 private int grade;
 
 public ClassRoom(int id, String name, int grade) {
  super();
  this.id = id;
  this.name = name;
  this.grade = grade;
 }
 
 public ClassRoom() {
  super();
 }

 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getGrade() {
  return grade;
 }
 public void setGrade(int grade) {
  this.grade = grade;
 }
}

 

Student.java

 

package com.sg.xml;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student {
 int id ;
 String name;
 int age ;
 ClassRoom classRoom;
 
 
 
 public Student() {
  super();
 }
 public Student(int id, String name, int age, ClassRoom classRoom) {
  super();
  this.id = id;
  this.name = name;
  this.age = age;
  this.classRoom = classRoom;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 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;
 }
 public ClassRoom getClassRoom() {
  return classRoom;
 }
 public void setClassRoom(ClassRoom classRoom) {
  this.classRoom = classRoom;
 }
}

 

下面是测试类:

 

package com.sg.xml;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.junit.Test;

public class TestJaxb {
 
 //创建xml
 @Test
 public void test01(){
  try {
   JAXBContext context = JAXBContext.newInstance(Student.class);
   Marshaller marshaller = context.createMarshaller();
   Student student = new Student(1, "孙刚", 20, new ClassRoom(1, "软件技术1002班", 2012));
   marshaller.marshal(student, new File("f:"+File.separator+"xml01.xml"));
  } catch (JAXBException e) {
   e.printStackTrace();
  }
 }
 //解析xml
 @Test
 public void test02(){
  File file = new File("f:"+File.separator+"xml01.xml");
  
  try {
   JAXBContext context = JAXBContext.newInstance(Student.class);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   
   Student student = (Student)unmarshaller.unmarshal(file);
   
   System.out.println(student.getName()+","+student.getClassRoom().getName());
  } catch (JAXBException e) {
   e.printStackTrace();
  }
  
 }
}

 

 

创建结果如下:

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student>
 <age>20</age>
  <classRoom>
   <grade>2012</grade>
   <id>1</id>
   <name>软件技术1002班</name>
  </classRoom>
 <id>1</id>
 <name>孙刚</name>
</student>