All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.xnx3.weixin.XmlUtil Maven / Gradle / Ivy

The newest version!
package com.xnx3.weixin;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.xnx3.StringUtil;

/**
 * XML简单工具类
 * @author 管雷鸣
 *
 */
public class XmlUtil {

    /**
     * 解析xml,返回第一级元素键值对。
     * @param strxml xml的字符串形式
     * @return Map形式
     */
    public static Map stringToMap(String strxml){
        if(null == strxml || "".equals(strxml)) {
            return null;
        }
        
        Map map = new HashMap();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document d = builder.parse(StringUtil.stringToInputStream(strxml, "UTF-8"));
			if(d.hasChildNodes()){
				Node node = d.getFirstChild();	//获取XML节点
				NodeList nodelist = node.getChildNodes();
				for (int i = 0; i < nodelist.getLength(); i++) {
					Node item = nodelist.item(i);
					map.put(item.getNodeName(), item.getTextContent());
				}
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        return map;
    }
    
    public static void main(String[] args) throws Exception {
		String xml = "1";
    	Map map = stringToMap(xml);
    	for(Map.Entry entry : map.entrySet()){
    	    String mapKey = entry.getKey();
    	    String mapValue = entry.getValue();
    	    System.out.println(mapKey+":"+mapValue);
    	}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy