利用SAX解析读取XML文件

来源:互联网 发布:linux echo写入 编辑:程序博客网 时间:2024/04/30 10:52
 

利用SAX解析读取XML文件

日期:2006-10-21  点击:295   作者:未知  来源:不详  

<script type="text/javascript"><!--google_ad_client = "pub-6302058902710134";google_alternate_color = "F9F9F9";google_ad_width = 468;google_ad_height = 15;google_ad_format = "468x15_0ads_al_s";//2006-11-22: 文章顶部google_ad_channel = "9037832944";google_color_border = "F9F9F9";google_color_bg = "F9F9F9";google_color_link = "000000";google_color_text = "000000";google_color_url = "008000";//--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>

 

 《J2EE应用开发详解》

  使用XML文件连接MYSQL数据库,database.conf.xml文件如下:

<database-conf>
<datasource>
 <driver>com.mysql.jdbc.Driver</driver>
 <url>jdbc:mysql://127.0.0.1:3306/j2ee14</url>
 <user>bn</user>
 <password>bn</password>
</datasource>
</database-conf>

新建一个Handler,用来解析该XML配置(ConfigParser.java) :

package com.j2ee14.ch4;
import  org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;

import java.util.Properties;

/**
 *ConfigParser扩展了DefaultHandler,它用于获得数据库的连接属性
 */
public class ConfigParser extends DefaultHandler
{
    //定义一个Properties 用来存放属性值
 private Properties props;
 private String currentName;
 private StringBuffer currentValue =new StringBuffer();
 
    //构建器初始化props
 
 public ConfigParser()
 {
  this.props=new Properties();
 }
 public Properties getProps()
 {
  return this.props;
 }
 
     //定义开始解析元素的方法. 这里是将<xxx>中的名称xxx提取出来
 
 public void startElement(String uri,String localName,String qName,Attributes attributes)throws SAXException
 {
  currentValue.delete(0,currentValue.length());
  this.currentName=qName;
 }
 
    //这里是将<xxx></xxx>之间的值加入到currentValue
 
 public void characters(char[] ch, int start, int length) throws SAXException {

 currentValue.append(ch, start, length);

 }

    /**
     *把XML配置文件的中相关的属性保存到Properties对象中
     */

 public void endElement(String uri,String localName,String qName)throws SAXException
 {
  props.put(qName.toLowerCase(),currentValue.toString().trim());
 }
}

用来解析XML的类,其他程序通过这个类来获得数据库的连接属性(ParseDatabaseConfig
.java):

package com.j2ee14.ch4;

import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 *其它程序通过ParseDatabaseConfig来获得数据库的配置信息,
 *这样使得类之间的耦合松散
 */
public class ParseDatabaseConfig
{
    //定义一个Properties 用来存放属性值
 private Properties props;
 
 public Properties getProps()
 {
  return this.props;
 }
 /**
  *解析XML配置文件,把属性保存起来
  */
 public void parse(String filename)throws Exception
 {
        //将我们的解析器对象化
  ConfigParser handler=new ConfigParser();
 
        //获取SAX工厂对象
  SAXParserFactory factory=SAXParserFactory.newInstance();
  factory.setNamespaceAware(false);
  factory.setValidating(false);
 
        //获取SAX解析
  SAXParser parser=factory.newSAXParser();
 
  try
  {
            //将解析器和解析对象xml联系起来,开始解析
   parser.parse(filename,handler);
  
            //获取解析成功后的属性
   props=handler.getProps();
  }
  finally
  {
   factory=null;
   parser=null;
   handler=null;
  }
 }

}

最后是一个数据库应用(MyDatabaseApplication
.java):

package com.j2ee14.ch4;

import java.util.Properties;
import java.sql.*;

/**
 *MyDatabaseApplication是一个示例应用,它通过ParseDatabaseConfig
 *来获得数据库的连接属性以连接数据库
 */
public class MyDatabaseApplication
{
 private Connection con;
 Properties dbProps;
 /**
  *构造方法,获得数据库的连接属性
  */
 public MyDatabaseApplication()throws Exception
 {
  ParseDatabaseConfig databaseConfig=new ParseDatabaseConfig();
  databaseConfig.parse("database.conf.xml");
  this.dbProps=databaseConfig.getProps();
 }
 public Connection getConnection()throws java.sql.SQLException
 {
  try
  {
   Class.forName(dbProps.getProperty("driver"));
  
  }
  catch(java.lang.ClassNotFoundException e)
  {
   System.err.println("Not Found Driver:"+dbProps.getProperty("driver"));
  }
  //使用配置的属性创建一个连接。
  return java.sql.DriverManager.getConnection(
         dbProps.getProperty("url"),
         dbProps.getProperty("user"),
         dbProps.getProperty("password"));
   }
  
   /**
    *测试方法
    */
   public void doBusiness()
   {
   
     try
     {
       con=getConnection();
       Statement stmt=con.createStatement();
       System.out.println("创建一个表...");
       stmt.execute("create table testconfig(id int not null,name varchar(20),constraint pk_testconfig primary key(id))");
        System.out.println("在表中添加数据...");
       stmt.execute("insert into testconfig values('001','hellking')");
       ResultSet rst=stmt.executeQuery("select * from testconfig");
       System.out.println("读取表中的数据...");
       while(rst.next())
       {
        System.out.println("id:"+rst.getInt("id"));
        System.out.println("name:"+rst.getString("name"));
       }
       rst.close();
       stmt.execute("drop table testconfig");
       con.close();
    }
    catch(java.sql.SQLException se)
    {
       System.err.println("连接数据库或者操作发生错误");
       se.printStackTrace(System.err);
    }
     
    finally
    {
       try
       {
        con.close();
       }
       catch(Exception e){}
    }
   }
  
   public static void main(String[] args)
   {
    System.out.println("使用XML作为数据库的配置。/n");

    try
    {
     MyDatabaseApplication app=new MyDatabaseApplication();
     app.doBusiness();
    }
    catch(Exception e)
    {
     System.err.println("发生异常");
    }
   }
   
   
}

原创粉丝点击