xml格式转换工具类

 


import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSONObject;
import com.lnlic.credit.common.core.constant.DataXmlConstant;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;

/**
 * xml格式转换工具类
 * 
 * @author Administrator
 *
 */
public class WebXmlUtil {
	
	private static Logger logger = Logger.getLogger(WebXmlUtil.class);  
	/**
	 * xml转换list
	 * 
	 * @return
	 * @throws DocumentException
	 */
	public static List> readStringXml(String xmlStr) {

    	List> list = new ArrayList>();
    	
    	Document document = null;
		try {
			document = DocumentHelper.parseText(xmlStr);
			
			Element rootElement = document.getRootElement();// 获取根节点
    	    
	    	getNodes(rootElement,list);
	    	
		} catch (DocumentException e) {
			
			logger.error("WebUtil_readStringXml: XML格式不正确,解析失败");
		}
    	 
		return list;
    }   	
	/**
	 * 递归遍历xml
	 * 
	 * @param rootElement
	 * @param list
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static void getNodes(Element rootElement,List list){
		
		//读取子节点配置
		Iterator iterator = rootElement.elementIterator();
		Element element=null;
		List> listData = null;
		while(iterator.hasNext()){
			element =(Element) iterator.next();
			if(DataXmlConstant.row.toLowerCase().equals(element.getName().toLowerCase())){
				listData = new  ArrayList();
				Iterator iteratororder = element.elementIterator();
				//将节点key和value放入map集合中
				LinkedHashMap personMap = new LinkedHashMap();
 				
				while(iteratororder.hasNext()){
					Element elementOrder = (Element) iteratororder.next();
					//获取节点name和value
					String eleName = elementOrder.getName();
					String eleValue = elementOrder.getTextTrim().trim();
					personMap.put(eleName, eleValue);
				}
				list.add(personMap);
			}
			//当前节点如果有子节点、递归
			Iterator iteratororder = element.elementIterator();
			if(iteratororder.hasNext()){
				getNodes(element,list);
			}
			
		}
				
	}
	
	/**
	 * js转xml格式
	 * 
	 * 此方法应用于js中的节点名称与xml中节点名称一致时。
	 * @param jsonobject
	 */
	public static String jsToXml(String [] str, JSONObject jsonObject){
		StringBuilder myStringBuilder = new StringBuilder();
		for(int i =0; i\n{0}\n\n", jsonObject.get(str[i])));
			}
		}	
		return myStringBuilder.toString();
	}
}

 

你可能感兴趣的:(xml格式转换工具类)