marshal(Java對(duì)象轉(zhuǎn)化成XML)
import javax.xml.bind.annotation.XmlRootElement; //指定根元素,其他屬性默許為根元素的子元素 @XmlRootElement(name="article") public class Article{ private String title; private String author; private String email; private String date; //省略setter和getter方法 }import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public static void main(String [] args){ File xmlFile = new File("E: est.xml"); JAXBContext context ; //聲明JAXBContext上下文對(duì)象 try{ //通過(guò)指定的類(lèi)創(chuàng)建上下文對(duì)象 context= JAXBContext.newInstance(Article.class); Marshaller marshaller =context.createMarshaller(); Article article = new Article(); article.setAuthor("Jerry"); article.setDate("2014⑼⑵1"); article.setEmail("Jerry@yahoo.com"); article.setTitle("XML概述"); //將Java對(duì)象轉(zhuǎn)換成xml文件 marshaller.marshal(article,xmlFile); }catch(JAXBException e){ e.printStackTrace(); } }
unmarshal(XML對(duì)象轉(zhuǎn)化成Java對(duì)象)
unmarshal是marshal的逆操作,與之類(lèi)似
context =JAXBContext.newInstance(Article.class); Unmarshal unmarshaller = context.createUnmarshaller(); Article article= (Article)unmarshaller.unmarshal(xmlFile);如xml文件有多個(gè)元素,可以創(chuàng)建1個(gè)新的Java對(duì)象,用List存儲(chǔ)子元素
@XmlRootElement public class Articles{ List<Article> articles = newArrayList<Article>; …… }