jaxbUtil

阅读更多
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 jaxbContextMap = new HashMap();

	/**
	 * 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 fromXml(String xml, Class 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 fromXML(String xml, Class 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  JAXBContext getJaxbContext(Class 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  Unmarshaller createUnmarshaller(Class clazz) {
		try {
			JAXBContext jaxbContext = getJaxbContext(clazz);
			return jaxbContext.createUnmarshaller();
		} catch (Exception e) {
			throw Exceptions.unchecked(e);
		}
	}

}

 

你可能感兴趣的:(xml)