`

jaxbUtil

    博客分类:
  • jaxb
xml 
阅读更多
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;

import com.h3c.itac.exception.Exceptions;

/**
 * Jaxb工具类
 */
public class JaxbUtil {

	@SuppressWarnings("rawtypes")
	static Map<Class, JAXBContext> jaxbContextMap = new HashMap<Class, JAXBContext>();

	/**
	 * JavaBean转换成xml
	 * 
	 * @param obj
	 * @param encoding
	 * @return
	 */
	public static String toXml(Object obj, String encoding, String path) {
		try {
			File file = new File(path);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream writer = new FileOutputStream(file);
			Marshaller marshaller = createMarshaller(obj, encoding);
			marshaller.marshal(obj, writer);
			return path;
		} catch (Exception e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * obj转xml时,忽略掉命名空间出现的ns2..nsN等前缀的情况
	 * 
	 * @param obj
	 *            待转对象
	 * @param encoding
	 *            编码
	 * @param ignoreNs
	 *            false:忽略前缀
	 * @return xml 路径
	 */
	public static String toXML(final Object obj, final String encoding,
			final boolean ignoreNs, final String path) {
		try {
			FileUtils.createDictionary(path);
			Marshaller marshaller = createMarshaller(obj, encoding);
			OutputStream out = new FileOutputStream(new File(path));
			OutputFormat format = new OutputFormat();
			format.setIndent(true);
			format.setNewlines(true);
			format.setNewLineAfterDeclaration(false);

			XMLWriter writer = new XMLWriter(out, format);
			XMLFilterImpl nsfFilter = new XMLFilterImpl() {
				private boolean ignoreNamespace = ignoreNs;
				private String rootNamespace = null;
				private boolean isRootElement = true;

				@Override
				public void startDocument() throws SAXException {
					super.startDocument();
				}

				@Override
				public void startElement(String uri, String localName,
						String qName, Attributes atts) throws SAXException {
					if (this.ignoreNamespace)
						uri = "";
					if (this.isRootElement)
						this.isRootElement = false;
					else if (!uri.equals("") && !localName.contains("xmlns"))
						localName = localName + " xmlns=\"" + uri + "\"";
					super.startElement(uri, localName, qName, atts);
				}

				@Override
				public void startPrefixMapping(String prefix, String uri)
						throws SAXException {
					if (this.rootNamespace != null)
						uri = this.rootNamespace;
					if (!this.ignoreNamespace)
						super.startPrefixMapping("", uri);
					else
						super.startPrefixMapping(prefix, uri);
				}

				@Override
				public void endElement(String uri, String localName,
						String qName) throws SAXException {
					if (this.ignoreNamespace)
						uri = "";

					super.endElement(uri, localName, qName);
				}
			};
			nsfFilter.setContentHandler(writer);
			marshaller.marshal(obj, nsfFilter);
			return path;
		} catch (JAXBException e) {
			throw Exceptions.unchecked(e);
		} catch (UnsupportedEncodingException e) {
			throw Exceptions.unchecked(e);
		} catch (FileNotFoundException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * xml转换成JavaBean
	 * 
	 * @param xml
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T fromXml(String xml, Class<T> clazz) {
		try {
			StringReader reader = new StringReader(xml);
			return (T) createUnmarshaller(clazz).unmarshal(reader);
		} catch (JAXBException e) {
			throw Exceptions.unchecked(e);
		}
	}

	/**
	 * 转xml为javabean对象
	 * 
	 * @param xml
	 *            xml文档内容
	 * @param clazz
	 *            bean对象类型
	 * @param isParserNamespace
	 *            是否解析命名空间
	 * @return 返回转换过后的javabean对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> T fromXML(String xml, Class<T> clazz,
			boolean isParserNamespace) {
		try {
			StringReader reader = new StringReader(xml);
			SAXParserFactory sax = SAXParserFactory.newInstance();
			sax.setNamespaceAware(isParserNamespace);
			XMLReader xmlReader = sax.newSAXParser().getXMLReader();
			Source source = new SAXSource(xmlReader, new InputSource(reader));
			return (T) createUnmarshaller(clazz).unmarshal(source);
		} catch (SAXException e) {
			throw Exceptions.unchecked(e);
		} catch (ParserConfigurationException e) {
			throw Exceptions.unchecked(e);
		} catch (JAXBException e) {
			throw Exceptions.unchecked(e);
		}
	}

	private static <T> JAXBContext getJaxbContext(Class<T> clazz) {
		JAXBContext jaxbContext = jaxbContextMap.get(clazz);
		try {
			if (jaxbContext == null) {
				jaxbContext = JAXBContext.newInstance(clazz);
				jaxbContextMap.put(clazz, jaxbContext);
			}
		} catch (JAXBException e) {
			throw new RuntimeException(
					"Could not instance JAXBContext for class [" + clazz + "],"
							+ e.getMessage(), e);
		}
		return jaxbContext;
	}

	private static Marshaller createMarshaller(Object obj, String encoding) {
		try {
			JAXBContext jaxbContext = getJaxbContext(obj.getClass());
			Marshaller marshaller = jaxbContext.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);// 是否格式化生成的xml串
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xml头信息
			return marshaller;
		} catch (JAXBException e) {
			throw Exceptions.unchecked(e);
		}
	}

	private static <T> Unmarshaller createUnmarshaller(Class<T> clazz) {
		try {
			JAXBContext jaxbContext = getJaxbContext(clazz);
			return jaxbContext.createUnmarshaller();
		} catch (Exception e) {
			throw Exceptions.unchecked(e);
		}
	}

}

 

分享到:
评论

相关推荐

    JAXBUtil使用JAXB进行xml和bean互转

    本篇文章将深入探讨如何使用JAXBUtil来实现XML和bean之间的互转,并基于提供的文件`JaxbObjectAndXmlUtil.java`和`ReqMsBean.java`进行实例解析。 首先,我们来看`ReqMsBean.java`,这是一个简单的Java Bean定义,...

    JaxbUtil.zip_jaxb

    JAXBUtil.zip_jaxb这个压缩包包含了一些帮助类,用于实现XML与JavaBean之间的便捷转换。在实际开发中,这种功能非常常见,特别是在处理XML格式的数据时,如配置文件、数据交换或者网络通信等场景。 首先,我们来看`...

    JaxbUtil.java

    JAXB工具类,xml和java对象相互转换的工具类,支持List直接转xml

    java 使用 JAXB 将xml转换为 bean 包含xml和dto和读取文件的util类

    Java中的JAXB(Java Architecture for XML Binding)是一个用于在Java对象和XML文档之间进行映射的标准API。这个技术使得开发者可以方便地将XML数据转换为Java对象,反之亦然。在给定的压缩包文件中,可能包含了实现...

    JAXB jar包 工具

    Java Architecture for XML Binding (JAXB) 是Java平台上的一个标准技术,它允许程序开发者将XML文档和Java对象之间进行绑定,实现XML数据的解析、序列化以及对象的创建。JAXB提供了一种从XML Schema(XSD)到Java类...

    lightgbm模型保存为pmml文件 机器学习lgbm模型存为pmml文件 通过java调用jar

    Evaluator evaluator = EvaluatorFactory.newInstance().createEvaluator(JAXBUtil.unmarshalPMML(FileReader.class.getResourceAsStream("/path/to/model.pmml"))); // 准备输入数据 Map, Object&gt; inputs = new...

    jaxb最新版本2.2.6

    Java Architecture for XML Binding (JAXB) 是Java平台上的一个标准技术,用于在Java对象和XML文档之间进行数据绑定。它允许开发者将XML Schema定义的数据结构直接映射到Java类,从而简化了XML文档的处理。...

    使用JAXB(用于XML绑定的Java API)解决现实世界问题的7个步骤

    JAXB(Java Architecture for XML Binding)是Java平台上的一个标准API,用于在Java对象和XML文档之间进行数据绑定。这个强大的工具使得开发人员能够轻松地处理XML数据,无需手动解析XML文档或创建复杂的序列化代码...

    lightgbm_pmml_demo:从python导出的受过训练的lightgbm模型,以供Java调用

    JPMMLModel jpmmlModel = JAXBUtil.unmarshalPMMLResource(new File("lightgbm.pmml")); // 获取ModelManager,它是模型管理和评估的核心接口 PMMLManager modelManager = new PMMLManager(jpmmlModel); // ...

Global site tag (gtag.js) - Google Analytics