JAXB

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>

 

  

  使用方法之解组

        前提:创建对应的javabean

        1.获取JAXBcontext对象

        2.创建解组组 Unmarshaller

        3.创建File文件对象

        4.强转为相应的类对象

        5.获取相应对象的值

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

 

posted @ 2016-09-17 16:50  学无止境小胡  阅读(296)  评论(0编辑  收藏  举报