java jaxb

来源:互联网 发布:广告设计软件学习 编辑:程序博客网 时间:2024/05/17 00:58

/** * 方法convertToXml的详细说明 * JAXB公用方法,通过接收XML对象,转换成XML字符串 * @param 参数类型 参数名 说明 * @return String 说明 * @throws 异常类型 说明 */public static String convertToXml(Object obj) {String encoding = "UTF-8";        String result = 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);              result = writer.toString();          } catch (Exception e) {              e.printStackTrace();          }          return result;      }

/** * * xml转javaBean通用方法 <br><pre> * 方法Xml2JBean的详细说明 <br> * @param sourceXml 待转换xml报文 * @param target 目标类 * @return * @throws JAXBException * @return T 说明 * @throws 异常类型 说明 */public static<T> T Xml2JBean(String sourceXml,Class<T> target) throws JAXBException {JAXBContext context = JAXBContext.newInstance(target); Unmarshaller unmarshaller = context.createUnmarshaller();  @SuppressWarnings("unchecked")T result = (T) unmarshaller.unmarshal(new StringReader(sourceXml));return result;}


0 0