首页 / XML / JAXB 操作XML 与 Object
JAXB 操作XML 与 Object
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JAXB 操作XML 与 Object,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2117字,纯文字阅读大概需要4分钟。
内容图文
Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。是一种xml与object映射绑定技术标准。
JDK5以下开发需要的jar包:activation.jar、jaxb-api.jar、 jaxb-impl.jar、 jsr173-api.jar
JDK6以上版本已经集成JAXB2的JAR,在目录{JDK_HOME}/jre/lib/rt.jar中。
@XmlAccessorType 注解 的枚举常量值说明:
代码片段:
* xml字符串 转 pojo * * @param t * @param xmlStr * @return */ @SuppressWarnings("rawtypes") public static Object jaxbReadXml(Class cls, String xmlStr) { ByteArrayInputStream stream = null; try { JAXBContext context = JAXBContext.newInstance(cls); stream = new ByteArrayInputStream(xmlStr.getBytes("utf-8")); Unmarshaller um = context.createUnmarshaller(); return um.unmarshal(stream); } catch (Exception e) { e.printStackTrace(); logger.error("----xml转对象出错:"+e.getMessage()); } finally { if (stream != null) { try { stream.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; } @SuppressWarnings("rawtypes") public static Object jaxbReadXml(Class cls, byte[] bs) { return jaxbReadXml(cls, new ByteArrayInputStream(bs)); } @SuppressWarnings("rawtypes") public static Object jaxbReadXml(Class cls, InputStream in) { try { JAXBContext context = JAXBContext.newInstance(cls); Unmarshaller um = context.createUnmarshaller(); return um.unmarshal(in); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } } return null; } /** * pojo 转 xml字符串 * * @param pojo * @return */ public static <T> String jaxbWriteXml(T pojo) { StringWriter out = null; String xmlStr = null; try { JAXBContext context = JAXBContext.newInstance(pojo.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); out = new StringWriter(); marshaller.marshal(pojo, out); xmlStr = out.toString(); // System.out.println(xmlStr); } catch (Exception e) { e.printStackTrace(); logger.error("----对象转xml出错:"+e.getMessage()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } return xmlStr; }
原文:http://blog.csdn.net/wuseyukui/article/details/40398725
内容总结
以上是互联网集市为您收集整理的JAXB 操作XML 与 Object全部内容,希望文章能够帮你解决JAXB 操作XML 与 Object所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。