赞
踩
- <?xml version="1.0" encoding="utf-8" ?>
- <DATA>
- <ENTITY>
- <FCCODE>1001</FCCODE>
- <MTCODE>SDSD</MTCODE>
- <CURRSTOCK>1234566</CURRSTOCK>
- <UPLOADTIME>2016-08-10 15:26:14</UPLOADTIME>
- </ENTITY>
- <ENTITY>
- <FCCODE>1002</FCCODE>
- <MTCODE>GRDFF</MTCODE>
- <CURRSTOCK>L6T7824SXGN175448</CURRSTOCK>
- <UPLOADTIME>2016-08-10 15:26:14</UPLOADTIME>
- </ENTITY>
- </DATA>
在dom4j的API中, xml文件下的所有节点都是elment,无论是跟节点还是子元素节点
Element root = doc.getRootElement(); 、//获取根节点,即DATA
List<Element> elements = root.elements(); // //获取根节点下的所有子元素 ,即所有的ENTITY
// 遍历所有子元素,即遍历出单个的一个个ENTITY
for(Element element:elements) {
遍历出每个ENTITY里面的子元素,.getTextTrim()---这个方法是得到元素的内容,将他们放到list中
for(Iterator<Element> it = element.elementIterator();it.hasNext();){
Element e = it.next();
list.add(e.getTextTrim());
}
特别说明,attribute()这个方法是表示某个元素的属性,如<ENTITY id='aaa' name='aaa'>,id就是第一个属性,name是他的第二个属性,还有attributes(),得到所有的属性集合
具体解析的代码如下,下面的代码是调用别人的webservice,然后穿回来的xml报文,将他解析,然后读取其中属性的内容讲他存入数据库
需要自己建对用属性的表和实体类
- public static List<EngineLineStock> xmlStrToElsList(String xmlStr) throws Exception {
- List<Object> list=new ArrayList<Object>();
- List<EngineLineStock> elsList=new ArrayList<EngineLineStock>();
- Map<String, Object> map = new LinkedHashMap<String, Object>();
- //将xml格式的字符串转换成Document对象
- Document doc = DocumentHelper.parseText(xmlStr);
- //获取根节点
- Element root = doc.getRootElement();
- //获取根节点下的所有子元素
- List<Element> elements = root.elements();
- //循环所有子元素
- if(elements != null && elements.size() > 0) {
- for(Element element:elements) {
- for(Iterator<Element> it = element.elementIterator();it.hasNext();){
- Element e = it.next();
- list.add(e.getTextTrim());
- }
- EngineLineStock s=new EngineLineStock();
- s.setFcCode((String) list.get(0));
- s.setMtCode((String) list.get(1));
- s.setCurrStock((String) list.get(2));
- s.setUploadTime((String) list.get(3));
- elsList.add(s);
- list.clear();
-
- }
- }
- return elsList;
-
-
- }
- public APIResponse<String> insertELS() throws Exception{
-
- String xmlStr="<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
- "<DATA>"+
- "<ENTITY>"+
- "<FCCODE>1001</FCCODE>"+
- "<MTCODE>SDSD</MTCODE>"+
- "<CURRSTOCK>1234566</CURRSTOCK>"+
- "<UPLOADTIME>2016-08-10 15:26:14</UPLOADTIME>"+
- "</ENTITY>"+
- "<ENTITY>"+
- "<FCCODE>1002</FCCODE>"+
- "<MTCODE>dfgb</MTCODE>"+
- "<CURRSTOCK>545435</CURRSTOCK>"+
- "<UPLOADTIME>2016-08-10 15:26:14</UPLOADTIME>"+
- "</ENTITY>"+
- "</DATA>";
- List<EngineLineStock> elsList=ParseXml.xmlStrToElsList(xmlStr);
-
-
-
- for(EngineLineStock els:elsList){
- engineLineStockService.insertEngineLineStock(els);
- }
-
- return APIResponse.success("成功");
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。