xml工具类-dom4j方式

前端之家收集整理的这篇文章主要介绍了xml工具类-dom4j方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
jar包下载地址:http://pan.baidu.com/s/1dD0DgTr?errno=0&errmsg=Auth%20Login%20Sucess&stoken=17b2287b172e1e1b350fa068bc320ec708a9b3e894e7296250f1b89e819f421907a081eb3ec99a1ccc44ab7fc81ff120cdd4851c7450817d32e184fcb965f37638001cd25e54&bduss=a0423543ea81540eaf034bb87ff7bd1a673e0c87c4d6de6219767c38ea9449e00532047c0713424d6d0c2fa047f7f64f55a3cf768d17d35d21c6792c764b2db30f80296903684e935a76668db9b3f8c9f1d87c5bd2cc5473678673b1d228325f2df274051e791b25f2c6d9b4d034924b1cea44720b551f522bd7160652a38e6b4a851640396f9e93d02424b8674f7c55035c9d5fb8499098a7624e3aa82470a2df78f8585583a1a00f1b3a4b9e21e75762c52dafe06ada5388d07a2c9935441d227eb6613509&ssnerror=0#list/path=%2F%E5%BC%80%E6%BA%90jar%E5%8C%85%E5%A4%A7%E5%85%A8%2F%E5%85%B6%E5%AE%83&parentPath=%2F%E5%BC%80%E6%BA%90jar%E5%8C%85%E5%A4%A7%E5%85%A8
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.apache.commons.lang.StringEscapeUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;


public class XmlConverUtil {
	/**
	 * Map转XML
	 * 
	 * @param map
	 * @return
	 */
	public static String maptoXml(Map map) {
		Document document = DocumentHelper.createDocument();
		Element nodeElement = document.addElement("xml");
		for (Object obj : map.keySet()) {
			Element keyElement = nodeElement.addElement(obj.toString());
			keyElement.setText("<![CDATA[" + String.valueOf(map.get(obj)) + "]]>");
		}
		return StringEscapeUtils.unescapeXml(document.getRootElement().asXML());
	}


	/**
	 * List转XML
	 * 
	 * @param list
	 * @return
	 */
	public static String listtoXml(List list) throws Exception {
		Document document = DocumentHelper.createDocument();
		Element nodesElement = document.addElement("nodes");
		int i = 0;
		for (Object o : list) {
			Element nodeElement = nodesElement.addElement("node");
			if (o instanceof Map) {
				for (Object obj : ((Map) o).keySet()) {
					Element keyElement = nodeElement.addElement("key");
					keyElement.addAttribute("label",String.valueOf(obj));
					keyElement.setText(String.valueOf(((Map) o).get(obj)));
				}
			} else {
				Element keyElement = nodeElement.addElement("key");
				keyElement.addAttribute("label",String.valueOf(i));
				keyElement.setText(String.valueOf(o));
			}
			i++;
		}
		return doc2String(document);
	}


	/**
	 * XML转Map
	 * 
	 * @param xml
	 * @return
	 */
	public static Map xmltoMap(String xml) {
		try {
			Map map = new HashMap();
			Document document = DocumentHelper.parseText(xml);
			Element nodeElement = document.getRootElement();
			List node = nodeElement.elements();
			for (Iterator it = node.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				map.put(elm.attributeValue(elm.getName()),elm.getText());
				elm = null;
			}
			node = null;
			nodeElement = null;
			document = null;
			return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * XML转List
	 * 
	 * @param xml
	 * @return
	 */
	public static List xmltoList(String xml) {
		try {
			List<Map> list = new ArrayList<Map>();
			Document document = DocumentHelper.parseText(xml);
			Element nodesElement = document.getRootElement();
			List nodes = nodesElement.elements();
			for (Iterator its = nodes.iterator(); its.hasNext();) {
				Element nodeElement = (Element) its.next();
				Map map = xmltoMap(nodeElement.asXML());
				list.add(map);
				map = null;
			}
			nodes = null;
			nodesElement = null;
			document = null;
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * @param document
	 * @return
	 */
	public static String doc2String(Document document) {
		String s = "";
		try {
			// 使用输出流来进行转化
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			// 使用UTF-8编码
			OutputFormat format = new OutputFormat("   ",true,"UTF-8");
			XMLWriter writer = new XMLWriter(out,format);
			writer.write(document);
			s = out.toString("UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return StringEscapeUtils.unescapeXml(s);
	}


	public static Map<String,String> parseXml(HttpServletRequest request) throws Exception {
		// 解析结果存储在HashMap
		Map<String,String> map = new HashMap<String,String>();
		InputStream inputStream = request.getInputStream();
		// 读取输入流
		SAXReader reader = new SAXReader();
		Document document = reader.read(inputStream);
		// 得到xml根元素
		Element root = document.getRootElement();
		// 得到根元素的所有子节点
		List<Element> elementList = root.elements();


		// 遍历所有子节点
		for (Element e : elementList)
			map.put(e.getName(),e.getText());


		// 释放资源
		inputStream.close();
		inputStream = null;


		return map;
	}


	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}


		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		org.jdom.Document doc = builder.build(in);
		org.jdom.Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			org.jdom.Element e = (org.jdom.Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}


			m.put(k,v);
		}


		// 关闭流
		in.close();


		return m;
	}


	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				org.jdom.Element e = (org.jdom.Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}


		return sb.toString();
	}


	public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}
}
原文链接:https://www.f2er.com/xml/294576.html

猜你在找的XML相关文章