pom.xml中加入jar包:
<!-- https://mvnrepository.com/artifact/dom4j/dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
java class
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element;
@ResponseBody @RequestMapping(value="/uploadClient") public Map<String, Object> getCustinfo(@RequestBody String body){ Map<String, Object> resultMap = new HashMap<String, Object>(); try { body = java.net.URLDecoder.decode(body, "UTF-8");//中文乱码问题 } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } logger.info("获取xml的内容:"+body); if(!body.equals("")){ body= body.substring(body.indexOf("<xml>"), body.indexOf("</xml>")+6); //确保开头结尾为<xml>和</xml> try { Document doc = DocumentHelper.parseText(body); Element rootElt = doc.getRootElement(); Iterator<Element> customers = rootElt.elementIterator("customer");// 获取根节点下所有customer String registUrl = PropertiesUtil.getValue("autoRegisterToiZhuan"); Map<String, Object> params = new HashMap<String, Object>(); while (customers.hasNext()) { Element cust = (Element) customers.next(); String mobile = cust.elementTextTrim("mobile"); String nickName = cust.elementTextTrim("custName"); // Iterator<Element> params = cust.elementIterator();//遍历customer下的子属性 // while(params.hasNext()){ // Element param = (Element) params.next(); // System.out.println(param.getName()+":"+param.getText()); // } } } catch (DocumentException e) { e.printStackTrace(); }; } return resultMap; }
xml的格式如下:
<![CDATA[<xml>
<customer>
<custName>张三</custName>
<gender>男</gender>
<birthday>19980211</birthday>
<mobile>13666666666</mobile>
<remark>备用</remark>
</customer>
<customer>
...
</customer>
</xml>]]>