Java SAX解析器解析XML設定檔

來源:互聯網
上載者:User
 

Java SAX解析器解析XML設定檔

最近,TL叫我做公司項目的技術積累。今天叫我完成下用SAX解析器解析XML設定檔。原來我一直是做的.net項目。最近剛轉到Java組裡來。我想。TL是不是有待我啊。給了我一份閑差,我開心。.net中解析個XML,實在是很舒服。三兩下就搞定的。我一直覺得Java和.net沒什麼根本上的差異的。於是。我便不緊不慢的做著。首先上網過google一下,好多的文章。我是在開心。可是當我看了10分鐘後,我鬱悶。發現幾乎所有的都是一樣的。而且我調了好久,愣是沒調出來。於是我決定自己寫。相信別人,不如信自己的。一番奮戰,終於搞定,分享一下吧。代碼如下:

/*
 * 從XML檔案中讀取配置資訊,並通過配置資訊返回資料庫連接
 *
 */
package com.augow.xmlconfigreader;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.SAXException;
import java.util.Properties;

/*
 * SAX方式用於解析XML檔案的解析器
 */

public class ConfigParser extends DefaultHandler
{
    /*props:用於存放解析器解析出來的的節點和節點對應的屬性,為雜湊表
     * currentName:當前節點的名稱
     * currentValue:用於存放當前節點所對應的屬性值
     */
    private Properties props;
    private String currentName;
    private StringBuffer currentValue = new StringBuffer();

   
 public ConfigParser()
    {
        this.props=new Properties();
    }
 
 
    public Properties getPrpos()
    {
        return this.props;
    }
   
   
    public String getCurrentName()
    {
        return currentName;
    }
   
   
    /*
     * 讀取<xxx>中的值xxx並將其付給qname,通知解析器解析當前節點對應的值。同時對currentValue緩衝器清空,用來儲存當前qname對應屬性值。
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
   public void startElement(String uri,String localName,String qName,Attributes attributes)
    throws SAXException
    {
        currentValue.delete(0,currentValue.length());
        this.currentName=qName;
    }
   
   
      /*讀取<xxx></xxx>之間的屬性值,並將其首先以字元形式儲存至字元數組ch中,並記錄對應長度,以確保以
       * length為長度的字元為一個整體,然後講字元數組中的內容按照length長度為整體加到currentValue緩衝器中
       * 每次讀取xml檔案後只會在ch中儲存當前所解析到的值,currentValue中也只會有當前的節點所對應的唯一值
     */
    public void characters(char[] ch,int start,int length)
    throws SAXException
    {
        currentValue.append(ch,start,length);
    }
   
   
     /* 當遇到</xxx>時,將當前的qname,和qname所對應的位於currentValue緩衝器中的值儲存到props這個雜湊表中去,供外部程式調用
     * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName)
    throws SAXException
    {
        props.put(qName.toLowerCase(), currentValue.toString().trim());
    }

 

}

 /*
 * 從XML檔案中讀取配置資訊,並通過配置資訊返回資料庫連接
 *
 */

package com.augow.xmlconfigreader;

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

/*
 * 用於執行個體化解析器,並利用解析器對XML檔案進行解析並將解析結果返回,通過提供的擷取結果的
 * 方法供外部程式調用
 */
public class XmlReader
{
    //用於存放解析結果的雜湊表
    private Properties props;
   
    public XmlReader(String filename)
    {
        try
            {
                parse(filename);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
       
    public Properties getProps()
    {
        return this.props;
    }
   
   
    /*
     * 用於分析xml檔案的方法
     */
    public  void parse(String filename)
    throws Exception
    {
        //執行個體化解析器
        ConfigParser handler = new ConfigParser();
       
        //執行個體化用於分析的工廠
        SAXParserFactory factory = SAXParserFactory.newInstance();
       
        //執行個體化分析類
        SAXParser parser = factory.newSAXParser();
       
        //得到xml檔案對應的路徑
        URL confURL = XmlReader.class.getClassLoader().getResource(filename);
        try
        {
            parser.parse(confURL.toString(), handler);
            props = handler.getPrpos();
        }
        finally
        {
            /*
             *銷毀已到期對象
             */
            factory=null;
            parser=null;
            handler=null;
        }

    }
   
   
    /*
     * 提供給外部程式調用的用於返回程式所對應需要的xml檔案屬性的方法
     */
    public String getElementValue(String elementName)
    {
        //elementValue:對應於elementName的節點的屬性值
        String elementValue=null;
        elementValue=props.getProperty(elementName);
        return elementValue;
    }
}

 

/*
 * 從XML檔案中讀取配置資訊,並通過配置資訊返回資料庫連接
 *
 */
package com.augow.xmlconfigreader;

import java.sql.*;

/*
 * 用於建立並返回由指定Xml設定檔所配置的資料庫連接
 */
public  class DBConnection
{
    private  static Connection conn=null;
    public DBConnection(){}
    /*
     * 建立指定的資料庫連接
     */
    public static Connection CreateConnection()
    {
        XmlReader p=new XmlReader("XMLConfigure.xml");
        try
        {   
            /*
             * 加入jdbc驅動包
             */
            Class.forName(p.getElementValue("dbtype")).newInstance();
            System.out.println("Success loading "+p.getElementValue("dbtype"));
        }catch(Exception e)
        {
            System.out.println("Error loading "+p.getElementValue("dbtype"));
        }
        try
        {
            conn=DriverManager.getConnection("jdbc:mysql://"+
                    p.getElementValue("dbhost")+"/"+p.getElementValue("dbname")+
                    "?user="+p.getElementValue("dbuser")+"&password="+
                    p.getElementValue("dbpassword")+"&characterEncoding=gb2312");
            System.out.println("Success connect Database!");
            System.out.println("Success return a connection to the database!");
            return conn;
        }catch(SQLException e)
        {
          System.out.println(e.getMessage());
          return null;
        }
       
    }

}

/*
 * 從XML檔案中讀取配置資訊,並通過配置資訊返回資料庫連接
 *
 */
package com.augow.xmlconfigreader;
import java.sql.*;

/*
 * 用於測試
 */
public class Test
{

    private static Statement stat=null;
    public static void main(String[] args)
    {

        Connection con=DBConnection.CreateConnection();
        try
        {
            ResultSet rs = null;
            stat= con.createStatement();
            rs=stat.executeQuery("select sname from student where snum='0202'");
            while(rs.next())
            {
              System.out.println(rs.getString("sname"));

            }
          con.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
              
    }

}

我連資料庫連接,測試類別,一股腦上來了,希望能幫到那些有需要的兄弟~~~~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.