XML java解析出来后 分别insert进mysql数据库
<?xml version="1.0" encoding="utf-8"?> <root> <Sentences> <DeptKind> <name>1</name> <PartKind> <name>1.1</name> <SickKind> <name>1.1.1</name> <Sentence> <Report><![CDATA[ 1.1.1.1内容]]></Report> <Conclusion><![CDATA[1.1.1.2内容]]></Conclusion> </Sentence> </SickKind> </PartKind> </DeptKind> <DeptKind> <name>2</name> <PartKind> <name>2.1</name> <SickKind> <name>2.1.1</name> <Sentence> <Report><![CDATA[ 2.1.1.1内容]]></Report> <Conclusion><![CDATA[2.1.1.2内容]]></Conclusion> </Sentence> </SickKind> </PartKind> </DeptKind> </Sentences> </root>
类似格式 这段xml解析。
public static void main(String[] args) throws Exception{ //插入数据的sql语句 String sql="insert into template_tab(name, name2, name, Report,Conclusion) values (?, ?, ?, ?, ?)"; Connection conn=null; PreparedStatement pstmt=null; try{ Class.forName("com.mysql.jdbc.Driver"); System.out.println("测试通过"); conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/pacs","root","root"); pstmt=conn.prepareStatement(sql); //读取xml文件 Document doc=new SAXReader().read(new File("D:/template2.xml")); //选择xml文件的节点 List itemList=doc.selectNodes("root/Sentences/DeptKind"); //遍历读出的xml中的节点 for(Iterator iter=itemList.iterator();iter.hasNext();){ Element el=(Element)iter.next(); //读取节点内容 String name=el.elementText("name"); List PartKind = el.elements("PartKind"); StringBuffer sbString=new StringBuffer(); //Element turnosElt=(Element)iter.next(); String name2 = ((Element) PartKind).elementText("name"); List SickKind = el.elements("SickKind"); Element turnosElt2=(Element)iter.next(); String name3 = turnosElt2.elementText("name"); //sbString.append(name3/* + "," + ma + "," + mi + "," + ju + "," + vi + "," + sa + "," + doo*/); //} List Sentence = el.elements("Sentence"); for(Iterator iter1=Sentence.iterator();iter1.hasNext();){ Element turnosElt3=(Element)iter1.next(); String Report = turnosElt3.elementText("Report"); //String Conclusion = PartKind.elementText("Conclusion"); //sbString.append(Report + "," + Conclusion ); } //为sql语句赋值 pstmt.setString(1, name); pstmt.setString(2, PartKind.toString()); pstmt.setString(3, SickKind.toString()); pstmt.setString(4, Sentence.toString()); pstmt.setString(5,sbString.toString()); pstmt.addBatch(); } pstmt.executeBatch(); System.out.print("将XML导入数据库成功"); }catch(Exception e){ e.printStackTrace(); }finally{ //DbUtil.close(pstmt); //.close(conn); //DbUtil.CloseDB(); //DbUtil.OpenDB(); conn.close(); } }
老是取不到下一个节点里面的 还报错 求修改
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论