码迷,mamicode.com
首页 > 编程语言 > 详细

JAXB(Java Architecture for XML Binding)

时间:2015-01-23 09:33:28      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:xml   jaxb   

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)

标签:xml   jaxb   

原文地址:http://blog.csdn.net/u012152619/article/details/43051085

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!