程序员人生 网站导航

JAXB(Java Architecture for XML Binding)

栏目:互联网时间:2015-01-29 08:34:26

marshal(Java对象转化成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上下文对象 try{ //通过指定的类创建上下文对象 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对象转换成xml文件 marshaller.marshal(article,xmlFile); }catch(JAXBException e){ e.printStackTrace(); } }


 

unmarshal(XML对象转化成Java对象)

unmarshal是marshal的逆操作,与之类似

context =JAXBContext.newInstance(Article.class); Unmarshal unmarshaller = context.createUnmarshaller(); Article article= (Article)unmarshaller.unmarshal(xmlFile);
 

如xml文件有多个元素,可以创建1个新的Java对象,用List存储子元素

@XmlRootElement public class Articles{ List<Article> articles = newArrayList<Article>; …… }


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐