依赖
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</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 = "<returnInfo><returnCode>-999</returnCode><description>error</description></returnInfo>";
}
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 = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"\n" +
"<Data>\n" +
" <Data_Row>\n" +
" <Lis_Barcode>0000000099</Lis_Barcode>\n" +
" <pat_id>42</pat_id>\n" +
" <pat_no>0000000099</pat_no>\n" +
" <blood_time/>\n" +
" <pat_name>张三丰</pat_name>\n" +
" <pat_bedno/>\n" +
" <pat_sex>男</pat_sex>\n" +
" <pat_birthday>1994-01-24 00:00:00.0</pat_birthday>\n" +
" <pat_age>0</pat_age>\n" +
" <pat_ageunit>4</pat_ageunit>\n" +
" <dept_name>信息科</dept_name>\n" +
" <doctor_name>zyf</doctor_name>\n" +
" <clinical_diag/>\n" +
" <samp_name>全血</samp_name>\n" +
" <LisItems>\n" +
" <lis_item_code>403</lis_item_code>\n" +
" <lis_item_name>白细胞</lis_item_name>\n" +
" <SubItems>\n" +
" <lis_subitem_code>350</lis_subitem_code>\n" +
" <lis_subitem_name>WBC</lis_subitem_name>\n" +
" </SubItems>\n" +
" </LisItems>\n" +
" <LisItems>\n" +
" <lis_item_code>961</lis_item_code>\n" +
" <lis_item_name>乙肝三系定量(5项)</lis_item_name>\n" +
" <SubItems>\n" +
" <lis_subitem_code>316</lis_subitem_code>\n" +
" <lis_subitem_name>HBsAg(定量)</lis_subitem_name>\n" +
" </SubItems>\n" +
" <SubItems>\n" +
" <lis_subitem_code>1115</lis_subitem_code>\n" +
" <lis_subitem_name>HBeAg(定量)</lis_subitem_name>\n" +
" </SubItems>\n" +
" <SubItems>\n" +
" <lis_subitem_code>547</lis_subitem_code>\n" +
" <lis_subitem_name>HBsAb(定量)</lis_subitem_name>\n" +
" </SubItems>\n" +
" <SubItems>\n" +
" <lis_subitem_code>796</lis_subitem_code>\n" +
" <lis_subitem_name>HBeAb(定量)</lis_subitem_name>\n" +
" </SubItems>\n" +
" <SubItems>\n" +
" <lis_subitem_code>233</lis_subitem_code>\n" +
" <lis_subitem_name>HBcAb(定量)</lis_subitem_name>\n" +
" </SubItems>\n" +
" </LisItems>\n" +
" </Data_Row>\n" +
"</Data>\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文档根节点元素,即最上层的"<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串:
<?xml version="1.0" encoding="UTF-8"?>
<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());//属性名及属性值
}
}
// 举例:获取<paralist name="noticelist">下的row节点
List<Node> rowNodes = doc.selectNodes( "//paralist[@name='noticelist']//row" );