日期:2014-05-16  浏览次数:20510 次

java语言连接mysql数据库并利用XML解析工具DOM生成XML文件,然后利用DOM SAX对所生成XML文件里的详细信息进行解析

//连接数据库并生成XML文件

import java.io.*;
import java.sql.*;
import java.io.FileOutputStream;
import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Document;


public class XmlTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  //int i=0;
  try {
   try {
         Class.forName("com.mysql.jdbc.Driver");
   } catch(ClassNotFoundException e) {
    System.out.println("加载驱动器类时出现异常");
    }
  try {
   File file=new File("C:/Users/chen/Desktop/studentinfo.xml");
   FileOutputStream fos = new FileOutputStream(file);  
   OutputFormat format = OutputFormat.createPrettyPrint();
   format.setEncoding("GB2312");

   XMLWriter writer =  new XMLWriter(fos,format);
   Document doc = DocumentHelper.createDocument();
   //Element rootElement=doc.addElement("学生信息");
   Element rootElement = DocumentHelper.createElement("学生信息");
   //rootElement.addAttribute("version", "2.0");
   doc.setRootElement(rootElement);
   java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","****");
   java.sql.Statement sql=conn.createStatement();
   java.sql.ResultSet rs=sql.executeQuery("select * from student");
   while(rs.next())
   {
       Element stu=rootElement.addElement("学生");
       Element id=stu.addElement("ID");
       Element name=stu.addElement("姓名");
       Element sex=stu.addElement("性别");
       Element begin=stu.addElement("入学年份");
       Element end=stu.addElement("毕业年份");
       id.addText(rs.getString(1));
       name.addText(rs.getString(2));
       sex.addText(rs.getString(3));
       begin.addText(rs.getString(4));
       end.addText(rs.getString(5));
   }
  
   writer.write(doc);
  } catch (IOException e) {
   e.printStackTrace();
  }
  } catch(SQLException e) {
   System.out.println("数据库连接时出现异常");
   } 
 }
}

 

//分析XML文件

import java.io.File;
import java.util.Iterator;
 
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class ParseXmlExample {   
    public void parseXmlDoc(String xmlFile){   
         SAXReader saxReader=new SAXReader();   
         Document doc=null;
         try{
         doc=saxReader.read(new File(xmlFile));
         }catch(DocumentException e){
          e.printStackT