JAXB实现Object与XML转换

前端之家收集整理的这篇文章主要介绍了JAXB实现Object与XML转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Customer类
@XmlRootElement(name = "type")
public class Customer {
 
	String name;
	int age;
	int id;
	
	public String getName() {
		return name;
	}
 
	@XmlElement
	public void setName(String name) {
		this.name = name;
	}
 
	public int getAge() {
		return age;
	}
 
	@XmlElement
	public void setAge(int age) {
		this.age = age;
	}
 
	public int getId() {
		return id;
	}
 
	@XmlAttribute
	public void setId(int id) {
		this.id = id;
	}
	
}
 
核心方法  JAXB
 
public class JAXB {


       /**
        * XML转Object
        * @param <T>
	* @param xmlStr
	* @param type
	* @return
	*/
	public static <T> T unmarshal(String xmlStr,Class<T> type){
		T customer = null;
		try {
			JAXBContext jaxbContext = JAXBContext.newInstance(type);
			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		  customer = (T) jaxbUnmarshaller.unmarshal(new StringReader(xmlStr));
			
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return customer;
	}
	
	/**
	* Object转XML
	* @param <T>
	* @param context
	* @param chart
	* @return
	* @throws JAXBException
	*/
	public static String marshal(Object obj,String encoding) {
		String strxml = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller(); 
	      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); 
	      marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding); 
	 	  StringWriter writer = new StringWriter(); 
	      marshaller.marshal(obj,writer); 
	      strxml = writer.toString(); 
		  } catch (JAXBException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
		}
	return strxml;
  }	
}
测试方法  JAXBTest 
public class JAXBTest {
public static void main(String args[]){
//xml转object
/*String xmlStr = "<?xml version=\"1.0\" encoding=\"gbk\" standalone=\"yes\"?><customer id=\"100\"><age>29</age><name>mkyong</name><sex>男</sex></customer>";
JAXB j = new JAXB();
Customer customer = j.unmarshal(xmlStr,Customer.class);
System.out.println(customer.name +" ; "+ customer.id +" ; "+ customer.age);*/
//object转xml
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
JAXB j = new JAXB();
String xml = j.marshal(customer,"UTF-8");
System.out.println(xml);
    }
}
原文链接:https://www.f2er.com/xml/298715.html

猜你在找的XML相关文章