本項目是一個webseriice的客戶端項目
Action 類:
SearchHotelRQ reqobj = XmlObjUtil.xml2Obj(reqstr, SearchHotelRQ.class); SearchHotelRS searchHotelRS = port.searchHotel(reqobj); resxml = XmlObjUtil.objToXmlString(searchHotelRS); return resxml;
對象轉為xml的方法:objToXmlString
public static <T> String objToXmlString(T obj) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(obj.getClass()); Marshaller m = jc.createMarshaller(); m.setProperty("jaxb.formatted.output", true); ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); m.marshal(obj, result); //轉碼 byte[] bystr = out.toByteArray(); String str = ""; try { str = new String(bystr,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } StringBuffer sb = new StringBuffer(str.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", "")); //log.error("JAXB transform object to string without version: "+ sb.toString()); return sb.toString(); }
第一種轉碼方式(在網上找的): m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");但在我這個項目中不起作用,不知為什么
第二種:上面方法中轉碼那一步,如果不轉碼,直接這么寫的話,StringBuffer sb = new StringBuffer(new String(out.toByteArray()).replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>", ""));取到的中文是亂碼