用 Jaxb 对 XML 和 JavaBean相互转换

用ConcurrentMap 对JAXBContext进行缓存,提高效率。


private static ConcurrentMap<Class<?>,JAXBContext> jaxbContexts = new ConcurrentHashMap<Class<?>,JAXBContext>();

	/**
	 * 把xml转换成对应的bean
	 * 
	 * @param <T>
	 * @param clazz
	 * @param xml
	 * @return
	 */
	public static <T> T parseXml2Bean(Class<T> clazz,String xml) {
		if (StringUtils.isBlank(xml)) {
			return null;
		}
		try {
			StringReader reader = new StringReader(xml);
			return clazz.cast(createUnmarshaller(clazz).unmarshal(reader));
		} catch (JAXBException e) {
			throw new RuntimeException("Could not parse xml to class [" + clazz + "]: " + e.getMessage(),e);
		}
	}

	/**
	 * 把bean转换成对应的xml
	 * 
	 * @param obj
	 * @return
	 */
	public static String parseBean2Xml(Object obj) {
		return parseBean2Xml(obj,null,false);
	}

	/**
	 * 是否省略xml头信息
	 * 
	 * @param obj
	 * @param encoding
	 *            编码格式
	 * @param bool
	 *            是否省略xml头信息
	 * @return
	 */
	public static String parseBean2Xml(Object obj,String encoding,boolean bool) {
		if (obj == null) {
			return null;
		}
		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			createMarshaller(obj.getClass(),encoding,bool).marshal(obj,os);
			return os.toString("UTF-8");
		} catch (JAXBException e) {
			throw new RuntimeException("Could not parse [" + obj + "] to xml " + e.getMessage(),e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}

	/**
	 * 创建Marshaller并设定encoding(可为null). <br/>
	 * 线程不安全,需要每次创建或pooling。
	 */
	private static Marshaller createMarshaller(Class<?> clazz,boolean bool) {
		try {
			JAXBContext jaxbContext = getJaxbContext(clazz);
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);// 是否格式化生成的xml串
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT,bool);// 是否省略xml头信息
			if (StringUtils.isNotBlank(encoding)) {
				marshaller.setProperty(Marshaller.JAXB_ENCODING,encoding);
			}
			return marshaller;
		} catch (JAXBException e) {
			throw new RuntimeException("Could not createMarshaller for class [" + clazz + "]: " + e.getMessage(),e);
		}
	}

	/**
	 * 创建UnMarshaller. <br/>
	 * 线程不安全,需要每次创建或pooling。
	 */
	private static Unmarshaller createUnmarshaller(Class<?> clazz) {
		try {
			JAXBContext jaxbContext = getJaxbContext(clazz);
			return jaxbContext.createUnmarshaller();
		} catch (JAXBException e) {
			throw new RuntimeException("Could not createUnmarshaller for class [" + clazz + "]: " + e.getMessage(),e);
		}
	}

	/**
	 * 维护jaxbContexts
	 */
	private static JAXBContext getJaxbContext(Class<?> clazz) {
		Validate.notNull(clazz,"'clazz' must not be null");
		JAXBContext jaxbContext = jaxbContexts.get(clazz);
		try {
			if (jaxbContext == null) {
				jaxbContext = JAXBContext.newInstance(clazz);
				JAXBContext j = jaxbContexts.putIfAbsent(clazz,jaxbContext);
				if (j != null) {
					jaxbContext = j;
				}
			}
		} catch (JAXBException e) {
			throw new RuntimeException(
					"Could not instantiate JAXBContext for class [" + clazz + "]: " + e.getMessage(),e);
		}
		return jaxbContext;
	}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


xml怎么加入图片路径
rss源错误怎么解决
文件后缀xml是什么意思
xml格式电子发票怎么获取
xml格式是什么意思
rss是什么意思啊
xml格式电子发票怎么打开
rss订阅源是什么意思
rss源是什么
xml注释怎么写
php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类