JAXB解析XML,将XML转化为OBJECT

前端之家收集整理的这篇文章主要介绍了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://www.jb51.cc/article/p-nvdrazml-bh.html

原文链接:https://www.f2er.com/xml/298869.html

猜你在找的XML相关文章