码迷,mamicode.com
首页 > 其他好文 > 详细

JAXB

时间:2016-09-17 17:41:05      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

jaxb:这是一种能将xml与java对象进行相互转化的技术,在jdk1.6之前这门技术属于j2ee部分,在jdk1.6的时候属于javase的部分了。

    使用方法之编组:

        1.创建一个javabean,并且在类的前面加上@XmlRootElement

        2.实例化一个java对象

         3.获取JAXBcontext对象

        4.创建编组 Marshaller

      代码示例如下:

package jaxb;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

import org.junit.Test;

import lombok.Data;

@XmlRootElement
@Data//使用lombok技术
public class Jaxb1 {
    private int id;
    private String name;
    private String number;
    public Jaxb1(){
        
    }
    
    @Test 
    public void print1() throws JAXBException{
        Jaxb1 j1 = new Jaxb1();
        j1.setId(12);
        j1.setName("huxuebing");
        j1.setNumber("201306002242");
        JAXBContext jaxbcontext = JAXBContext.newInstance(Jaxb1.class);
        Marshaller marshaller =jaxbcontext.createMarshaller();
        marshaller.marshal(j1, System.out);
    }
    
}



<?xml version="1.0" encoding="UTF-8" standalone="yes"?><jaxb1><id>12</id><name>huxuebing</name><number>201306002242</number></jaxb1>

 

  

  使用方法之解组

        1.获取JAXBcontext对象

        2.创建编组 Unmarshaller

        3.创建File文件对象

        4.获取

package jaxb;

import java.io.File;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.junit.Test;



public class Web {

    @Test
    public void print3() throws JAXBException{
        
        
    /*
        File xml = new File( "D:\\person.xml" );

        Person person = (Person) JAXB.unmarshal ( xml,Person.class );
        
        System. out .println( person.toString() );*/
        // 1. 创建JAXBContext
                JAXBContext context = JAXBContext.newInstance(Customer.class);
                // 2. 创建解组
                Unmarshaller unmarshaller = context.createUnmarshaller();
                File f = new File("web.xml");
                Customer c = (Customer)unmarshaller.unmarshal(f);
                
                System.out.println(c);
                
    }

}
jaxb.Customer@73a28541

 

JAXB

标签:

原文地址:http://www.cnblogs.com/huxuebing/p/5879102.html

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