加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

JAXB 操作XML 与 Object

发布时间:2020-12-16 06:39:41 所属栏目:百科 来源:网络整理
导读:Java Architecture for XML Binding) 是一个业界的标准,是一项可以根据XML Schema产生Java类的技术。是一种xml与object映射绑定技术标准。 JDK5以下开发需要的jar包:activation.jar、jaxb-api.jar、 jaxb-impl.jar、 jsr173-api.jar JDK6以上版本已经集成J

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;
	}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读