JAXB xml和java object的转换

JAXB提供了一种把Java object转成XML,或者把XML转成Java object的机制。
JAXB有两个过程,一个是unmarshalling,另一个是marshalling。
unmarshalling:reading。从XML instance转成Java content。
marshalling:writing。从Java content转成XML instance。

注解的含义
@XmlRootElement 指定了XML document的root element。
@XmlAttribute 指定了root element的attribute。
@XmlElement 指定了root element的sub-element。

object to xml 相关代码

  try {
            JAXBContext jContext = JAXBContext.newInstance(Student.class);
            Marshaller marshallObj = jContext.createMarshaller();
            marshallObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            Student student = new Student("abc", 123, "hadoop");
            marshallObj.marshal(student, new FileOutputStream("D:\\student.xml"));
        } catch(Exception e) {
            e.printStackTrace();
        }

xml to object 相关代码

try {
            JAXBContext jContext = JAXBContext.newInstance(Student.class);
            Unmarshaller unmarshallerObj = jContext.createUnmarshaller();
            Student student = (Student) unmarshallerObj.unmarshal(JAXB_Demo.class.getClassLoader().getResourceAsStream("config/student.xml"));
            System.out.println(student.getName()+":"+student.getId()+":"+student.getSubject());
        } catch(Exception e) {
            e.printStackTrace();
        }

参考资料://www.greatytc.com/p/6138d0a9709b

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。