jaxb的marshal和unmarshall使用

marshal

 /**
      * 对象转xml
      * 返回xml
      * @param tXLife
      * @return
      */
public static String tXLiftToXML(com.TXLife tXLife){
	String xml="";
    	try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			JAXBContext jc = JAXBContext
					.newInstance("com");  //包的命名空间
			Marshaller m = null;
			synchronized (jc) {
				m = jc.createMarshaller();
			}
			m.setProperty(Marshaller.JAXB_ENCODING, "GBK");
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			m.marshal(tXLife, out);

			xml=out.toString(); //赋值
		} catch (Exception e) {
			xml=null;
		}
    	return xml;
}

unmarshall

 /**
      * xml变对象
      * 封装撤单返回来的xml,只是一个OLifE
      * @param xml
      * @return
      */
     public static  com.TXLife xmlToTXLift(String xml){
    	 com.TXLife tx=null;
    	 if(null!=xml&&!"".equals(xml)){
    		 try {
    	 			JAXBDataBinding dataBinding = new JAXBDataBinding();
    	 			dataBinding
    	 					.setPkgNameBy(com.TXLife.class
    	 							.getName()); //命名空间
    	 			tx = (com.TXLife) dataBinding
    	 					.unmarshall(new ByteArrayInputStream(xml.getBytes("GBK")));
    	 		} catch (Exception e) {
    	 			e.printStackTrace();
    	 			tx = null;
    	 		}
    	 }
    	 return tx;
    	 
     }
 

 

你可能感兴趣的:(marshal)