xml 与 JavaBean的互转

在处理移动MMarket支付的时候,发现相关的类里使用了:@XmlRootElement 的注解·

搜索了一下,才知道JAXB:JAXB(Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生java类的技术


以下是互转的一些方法代码


	/**
	 * 将JAVA对象转为XML对象输出:注意:需使用jaXB的注解
	 * @return
	 * @throws JAXBException
	 */
	public static String java2XML(Object obj) throws JAXBException{		
		JAXBContext context =JAXBContext.newInstance(obj.getClass());
          Marshaller mar = context.createMarshaller();  
          mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);  
          mar.setProperty(Marshaller.JAXB_ENCODING,"UTF-8"); 
          StringWriter writer = new StringWriter();              
          mar.marshal(obj,writer);          
          return writer.toString();
	}
	
	/**
	 * xml转换为java对象
	 * @param xml
	 * @param c
	 * @return
	 * @throws JAXBException 
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xml2Java(String xml,Class<T> c) throws JAXBException {
		T t = null;
		JAXBContext context = JAXBContext.newInstance(c);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		t = (T) unmarshaller.unmarshal(new StringReader(xml));
		return t;
	}

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念