JAXB xml和java object的轉(zhuǎn)換

JAXB提供了一種把Java object轉(zhuǎn)成XML,或者把XML轉(zhuǎn)成Java object的機制。
JAXB有兩個過程,一個是unmarshalling,另一個是marshalling。
unmarshalling:reading。從XML instance轉(zhuǎn)成Java content。
marshalling:writing。從Java content轉(zhuǎn)成XML instance。

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

object to xml 相關(guān)代碼

  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 相關(guān)代碼

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

參考資料:http://www.itdecent.cn/p/6138d0a9709b

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容