xml和map相互转化

依赖


		<dependency>
			<groupId>dom4jgroupId>
			<artifactId>dom4jartifactId>
			<version>1.6.1version>
		dependency>
		
		<dependency>
			<groupId>jaxengroupId>
			<artifactId>jaxenartifactId>
			<version>1.1.6version>
		dependency>
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 java.io.StringReader;
import java.io.StringWriter;
import java.util.*;

public class MapToXml {
    public static String formatXML(String xml) {
        String requestXML = null;
        try {
            // 拿取解析器
            SAXReader reader = new SAXReader();
            Document document = reader.read(new StringReader(xml));
            if (null != document) {
                StringWriter stringWriter = new StringWriter();
                // 格式化,每一级前的空格
                OutputFormat format = new OutputFormat("    ", true);
                // xml声明与内容是否添加空行
                format.setNewLineAfterDeclaration(false);
                // 是否设置xml声明头部
                format.setSuppressDeclaration(false);
                // 是否分行
                format.setNewlines(true);
                XMLWriter writer = new XMLWriter(stringWriter, format);
                writer.write(document);
                writer.flush();
                writer.close();
                requestXML = stringWriter.getBuffer().toString();
            }
            return requestXML;
        } catch (Exception e) {
            System.out.println("格式化xml,失败 --> {}"+e);
            return null;
        }
    }
    public static String  parseMap(Map<?, ?> map, StringBuffer sb) {
        Set<?> set = map.keySet();
        for (Iterator<?> it = set.iterator(); it.hasNext();) {
            String key = (String) it.next();
            Object value = map.get(key);
            if (value instanceof HashMap) {
                sb.append("<" + key + ">");
                parseMap((HashMap<?, ?>) value, sb);
                sb.append(" + key + ">");
            } else if (value instanceof ArrayList) {
                List<?> list = (ArrayList<?>) map.get(key);
                for (int i = 0; i < list.size(); i++) {
                    sb.append("<" + key + ">");
                    Map<?, ?> hm = (HashMap<?, ?>) list.get(i);
                    parseMap(hm, sb);
                    sb.append(" + key + ">");
                }
            } else {
                sb.append("<" + key + ">" + value + " + key + ">");
            }
        }
        return sb.toString();
    }
	/**
	 * w3c Element 转成xml串
	 * @param element
	 * @return
	 * @throws Exception
	 */
	public static String w3cElementTransferXmlStr(org.w3c.dom.Element element) throws Exception{
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();
		Source source = new DOMSource(element);
		StringWriter out = new StringWriter();
		Result output = new StreamResult(out);
		transformer.transform(source, output);
		out.flush();
		String ss = out.toString();
		return formatXML(ss);
	}
	/**
	 *  xml串 转成w3c Element
	 * @param xmlString
	 * @return
	 * @throws Exception
	 */
	public static org.w3c.dom.Element getElementByString(String xmlString) throws Exception {
		if (xmlString == null){
			xmlString = "-999error";
		}
		org.w3c.dom.Document doc = null;
		Reader strreader = new StringReader(xmlString);
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		doc = builder.parse(new InputSource(strreader));
		return doc.getDocumentElement();
	}

}

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class XmlToMap {
    public static void main(String[] args) {
        String xml = "\n" +
                "\n" +
                "\n" +
                "  \n" +
                "    0000000099\n" +
                "    42\n" +
                "    0000000099\n" +
                "    \n" +
                "    张三丰\n" +
                "    \n" +
                "    \n" +
                "    1994-01-24 00:00:00.0\n" +
                "    0\n" +
                "    4\n" +
                "    信息科\n" +
                "    zyf\n" +
                "    \n" +
                "    全血\n" +
                "    \n" +
                "      403\n" +
                "      白细胞\n" +
                "      \n" +
                "        350\n" +
                "        WBC\n" +
                "      \n" +
                "    \n" +
                "    \n" +
                "      961\n" +
                "      乙肝三系定量(5项)\n" +
                "      \n" +
                "        316\n" +
                "        HBsAg(定量)\n" +
                "      \n" +
                "      \n" +
                "        1115\n" +
                "        HBeAg(定量)\n" +
                "      \n" +
                "      \n" +
                "        547\n" +
                "        HBsAb(定量)\n" +
                "      \n" +
                "      \n" +
                "        796\n" +
                "        HBeAb(定量)\n" +
                "      \n" +
                "      \n" +
                "        233\n" +
                "        HBcAb(定量)\n" +
                "      \n" +
                "    \n" +
                "  \n" +
                "\n";

        try {
            //xml转map
            Map map = parseXml(xml);
            System.out.println("+++++++++++++++++");

            //map转xml
            StringBuffer sb = new StringBuffer();
            MapToXml.parseMap(map,sb);
            System.out.println(MapToXml.formatXML(sb.toString()));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**
     * xml转为map,map中有list(节点相同时候),list中有map
     * @param xml
     * @return
     * @throws DocumentException
     */
    public static Map<String, Object> parseXml(String xml) throws DocumentException {
        Map map = new HashMap();
        try {
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));//xml串第一行不能有空格,否则报错
            Element root = document.getRootElement();//得到xml文档根节点元素,即最上层的""
            elementTomap(root, map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }

    @SuppressWarnings("unchecked")
    public static Map<String, Object> elementTomap(Element outele, Map<String, Object> outmap) {
        List<Element> list = outele.elements();
        int size = list.size();
        if (size == 0) {
            outmap.put(outele.getName(), outele.getTextTrim());
        } else {
            Map<String, Object> innermap = new HashMap<String, Object>();
            int i = 1;

            for (Element ele1 : list) {
                String eleName = ele1.getName();

                String value = ele1.getText();
                Object obj = innermap.get(eleName);
                if (obj == null) {
                    elementTomap(ele1, innermap);
                } else {
                    if (obj instanceof java.util.Map) {
                        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
                        list1.add((Map<String, Object>) innermap.remove(eleName));
                        elementTomap(ele1, innermap);
                        list1.add((Map<String, Object>) innermap.remove(eleName));
                        innermap.put(eleName, list1);
                    } else if (obj instanceof String) {

                        innermap.put(eleName + i, value);
                        i++;
                    } else {
                        elementTomap(ele1, innermap);
                        Map<String, Object> listValue = (Map<String, Object>) innermap.get(eleName);
                        ((List<Map<String, Object>>) obj).add(listValue);
                        innermap.put(eleName, obj);
                    }

                }
            }
            outmap.put(outele.getName(), innermap);
        }
        return outmap;
    }
}

获取节点的例子
xml串:


<soap:Envelope
    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <soap:Header>
        <in:system
            xmlns:in="http://www.molss.gov.cn/">
            <para funid="F01.01.01.02"/>
        in:system>
    soap:Header>
    <soap:Body>
        <in:business
            xmlns:in="http://www.molss.gov.cn/">
            <para channelid="fjfz0002"/>
            <para channelsign="031bfee38b647a041893a8ade78d8d2c34422"/>
            <para AAZ107="12316"/>
			<para AAZ501="A39714791"/>
            <para aae140="310"/>
			<para code="1"/>
			<para AKC021="2"/>
			<para AKA122="000002000001"/>
			<para AKE098="0"/>
			<para APA151="0"/>
			<para BPA150="1"/>
			<para BPA155=""/>
			<paralist name="noticelist">
                <row  AKE001="11401007206041510501" AKE006="汞溴红溶液"  AKA074="20ml" AKC229="1" />
				<row  AKE001="11401007206041510502" AKE006="波立维颗粒"  AKA074="1g" AKC229="1" />
            paralist>
            <paralist name="mxlist">
                <row AKE001="11401007206041510501"  AKE006="汞溴红溶液" AKC194="20190325 " AKE130=""  AKC226="1" AKC225="2" AKB065="2" AKA074="20ml" AKA072="1" AKA071="1ml" AKC229="3" AAC003="张明" AKB021="上海街道社区医院" AKA122="" AAE376="内科" />
            paralist>
        in:business>
    soap:Body>
soap:Envelope>

SAXReader saxReader = new SAXReader();
Document doc = saxReader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));//xml串第一行不能有空格,否则报错
List<Node> paraNodes = (List) doc.selectNodes("//para");//获取para节点
 for(Node e:paraNodes){
     List list = ((Element)e).attributes();//节点中的属性集合
     for (int i = 0; i < list.size(); i++){
         DefaultAttribute attribute = (DefaultAttribute)list.get(i);
         map.put(attribute.getName(), attribute.getValue());//属性名及属性值
     }
 }

// 举例:获取下的row节点
 List<Node> rowNodes = doc.selectNodes( "//paralist[@name='noticelist']//row" );

你可能感兴趣的:(没有分类)