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:\\test.xml"); JAXBContext context ; //声明JAXBContext上下文对象 try{ //通过指定的类创建上下文对象 context= JAXBContext.newInstance(Article.class); Marshaller marshaller =context.createMarshaller(); Article article = new Article(); article.setAuthor("Jerry"); article.setDate("2014-9-21"); 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文件有多个元素,可以创建一个新的Java对象,用List存储子元素
@XmlRootElement public class Articles{ List<Article> articles = newArrayList<Article>; …… }
JAXB(Java Architecture for XML Binding)
原文地址:http://blog.csdn.net/u012152619/article/details/43051085