JAXB转换xml和JavaBean

前端之家收集整理的这篇文章主要介绍了JAXB转换xml和JavaBean前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

鼓捣了一番,一开始各种出错,终于得以解决问题。下面晒晒吧(例子是存储学生)

学生类:

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "student")
public class student {
@XmlElement(name = "name")
public String name;
@XmlElement(name = "age")
public String age;

public List<String> score = new ArrayList();

public void setName(String name) {
this.name = name;
}


public void setAge(String age) {
this.age = age;
}

public void addscore(String s){

score.add(s);
}
}

学生的集合类:

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlList;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "students")
public class studnets {


@XmlElement(name = "stu")
public List<student> students = new ArrayList();

public List<student> addstu(student s){

students.add(s);
return students;

}
}

主类:

import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; public class testmain { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub student s = new student(); s.name = "dang"; s.age = "18"; s.addscore("100"); s.addscore("90"); student s2 = new student(); s2.name = "cha"; s2.age = "14"; s.addscore("100"); s.addscore("95"); studnets ss = new studnets(); ss.addstu(s); ss.addstu(s2); try { javatoxml(ss,new File("a.xml")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } File f=new File("a.xml"); try { studnets crb = (studnets) xmltojava(studnets.class,f); System.out.println(crb.students.get(0).name); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("不行喔"); } /* * 结果: * <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <students> <stu> <name>dang</name><age>18</age> <score>100</score><score>90</score> <score>100</score><score>95</score> </stu> <stu> <name>cha</name> <age>14</age> </stu> </students> */ } public static Object xmltojava(Class cls,File file) throws Exception{ JAXBContext ctx=JAXBContext.newInstance(cls); //JAXBContext可以创建 Unmarshallers(将XML解析为Java对象) Unmarshaller us=ctx.createUnmarshaller(); return us.unmarshal(file); } //*************JavaBeanàXML*********************** public static void javatoxml(Object obj,File file) throws Exception{ JAXBContext ctx=JAXBContext.newInstance(obj.getClass()); //JAXBContext可以创建Marshallers(将Java对象转换成XML) Marshaller mar=ctx.createMarshaller(); mar.marshal(obj,file); } } 好了,运行就行了,打完收工。

猜你在找的XML相关文章