<output> </row> </row> 求各位大神,怎么把这xml解释后,按属性param_name名,一条一条存进数据库?最好有例子。谢谢大家 |
|
楼主就别想要例子了
自己用dom4j解析吧 |
|
100分 |
//按照你的xml格式,用dom4j做的解析.,插入数据都不会的,自己百度 public static void main(String[] args) throws Exception { String readStr = ""; String text = ""; FileReader fr = new FileReader( "C:\Users\Administrator\Desktop\cal.html"); BufferedReader br = new BufferedReader(fr); while ((readStr = br.readLine()) != null) { text += readStr; } //读取完成xml System.out.println(text); Element element = getXmlRoot(text); Map map = new HashMap(); parse(element, null, map); System.out.println(map.get("reason")); List list = (List)map.get("results"); //遍历数据数据 for(Object o:list){ Map m = (Map)o; System.out.println(m.get("20052001")); System.out.println(m.get("20052002")); } } public static Element getXmlRoot(String str) throws DocumentException, IOException { StringReader sr = new StringReader(str); SAXReader saxReader = new SAXReader(); Document doc = saxReader.read(sr); Element root = doc.getRootElement(); return root; } //为了方便采用map封装,也可以用自己的javabean public static void parse(Element element, Element father,Map map) { if(father!=null){ if("output".equals(father.getName())){ if ("resultcode".equals(element.getName())||"reason".equals(element.getName())) { map.put(element.getName(), element.getStringValue()); } } //如果父节点是reslut,则当前节点是row, if("result".equals(father.getName())){ String rownum = element.attributeValue("rownum"); //对row下的元素遍历封装 List<Element> elements = element.elements(); Map<String,String> m = new HashMap<String,String>(); if (elements.size() > 0) { for (Element elem : elements) { if("col".equals(elem.getName())){ m.put(elem.attributeValue("param_name"),elem.getStringValue()); } } } List list = (List)map.get("results"); if(list==null){ list=new ArrayList(); } list.add(m); map.put("results",list); return; } } // 有子元素 List<Element> elements = element.elements(); if (elements.size() > 0) { for (Element elem : elements) { // 递归遍历 parse(elem, element,map); } } } |