JAXB解析XML,將XML轉化爲OBJECT

直接代碼:

package com.analysis.dome;

import java.beans.XMLDecoder;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;

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

public class Main {
	private static String xmlCoding="UTF-8";
	

	public static void main(String[] args) {
		String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><person><username>sunsz</username><age>26</age><sex>man</sex><personType>" +
				"<personType>工程師</personType><xxxx>123456</xxxx>" +
				"</personType></person>";
	       
		Person user = (Person) parseXmlDataObject(Person.class,xml);
		
		System.out.println(user.getUsername());
		System.out.println(user.getAge());
		System.out.println(user.getPersonType().getPersonType());
		System.out.println(user.getUsername());
		
		
	}
	
	//獲取OBJECT 實例
	@SuppressWarnings("unchecked")
	private static Unmarshaller createUnMarshallerByType(Class type){
	   Unmarshaller unMar = null;
	   try {
	    JAXBContext jax = JAXBContext.newInstance(type);
	    unMar = jax.createUnmarshaller();
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	   return unMar;
	}
	
	@SuppressWarnings("unchecked")
	public static Object parseXmlDataObject(Class type,String xmlData){
	   if(xmlData==null || xmlData.trim().length()==0)
	    return null;
	   try {
	    Unmarshaller unMar = createUnMarshallerByType(type);
	    ByteArrayInputStream bais = new ByteArrayInputStream(xmlData.getBytes(xmlCoding));
	    return unMar.unmarshal(bais);
	   } catch (Exception e) {
	    e.printStackTrace();
	   }
	   return null;
	}
}
代碼網上找的~,只爲測試一點,當XML中有OBJECT不存在的屬性時,是否報錯。記錄一下!


注意一點,OBJECT 需要配置 JAXB的註解。要不然會報錯~~


註解介紹:http://blog.csdn.net/lw371496536/article/details/6942045

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章