java 读取 xml 文件

Java
351
0
0
2022-09-14
1.DB.java

 package com.bn.util;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.Iterator;
 import java.util.Properties;
 import org.dom4j.Document;
 import org.dom4j.DocumentException;
 import org.dom4j.Element;
 import org.dom4j.io.SAXReader;
 public class DB {
 private static String dbServer;
 private static String dbName;
 private static String dbUser;
 private static String dbPwd;

/**
 * 说明:java读取xml
 * 作者:FH Admin
 * from:fhadmin.cn
 */ 
 public void readXML(){

     SAXReader sr = new SAXReader();//获取读取xml的对象。 
    Document doc = null;
     String path1 = String.valueOf(Thread.currentThread().getContextClassLoader().getResource(""));
     //System.out.println(path1);
     path1 = path1 + "../DB.xml";
     //System.out.println(path1); 
   try {
    doc = sr.read(path1);
   } catch (DocumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }//得到xml所在位置。然后开始读取。并将数据放入doc中 
    Element el_root = doc.getRootElement();//向外取数据,获取xml的根节点。 
    Iterator it = el_root.elementIterator();//从根节点下依次遍历,获取根节点下所有子节点

     while(it.hasNext()){//遍历该子节点

      Object o = it.next();//再获取该子节点下的子节点 
     Element el_row = (Element)o;
      String s = el_row.getText();
      Iterator it_row = el_row.elementIterator();
      int i =1;
      while(it_row.hasNext()){//遍历节点 
      Element el_ename = (Element)it_row.next();//获取该节点下的所有数据。

       if(i == 1){
        this.setDbServer(el_ename.getText());
        //System.out.println(this.getDbServer()); 
        //dbServer = el_ename.getText();
       }
       if(i == 2){
        this.setDbName(el_ename.getText());
         // System.out.println(this.getDbName()); 
        //dbName = el_ename.getText();
       }
       if(i == 3){
        this.setDbUser(el_ename.getText());
         // System.out.println(this.getDbUser()); 
        //dbUser = el_ename.getText();
       }
       if(i == 4){
        this.setDbPwd(el_ename.getText());
         // System.out.println(this.getDbPwd()); 
        //dbPwd = el_ename.getText();
       }
      // System.out.println(i);
       i++;
       //System.out.println(el_ename.getText());
      }
      //System.out.println(o);
     }

    }
 static {
   DB dbxml = new DB();
   dbxml.readXML();

   try {
    Class.forName("com.mysql.jdbc.Driver");
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   }
 }

 public static Connection createConn(){
   DB dbxml = new DB();
   //String name = dbxml.dbName; 
   //System.out.println(name); 
   //System.out.println(dbxml.getDbServer() + dbxml.getDbName() + dbxml.getDbUser() + dbxml.getDbPwd()); 
   Connection conn = null;
   try {
    conn = DriverManager.getConnection("jdbc:mysql://"+ dbxml.getDbServer() +":3306/"+ dbxml.getDbName() +"?user="+ dbxml.getDbUser() +"&password="+ dbxml.getDbPwd());
    //conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bnss?user=root&password=root");
   } catch (SQLException e) {
    e.printStackTrace();
   }
   return conn;
 }

 public static PreparedStatement createPstmt(Connection conn, String sql){
   PreparedStatement pstmt = null;
   try {
    pstmt = conn.prepareStatement(sql);
   } catch (SQLException e) {
    e.printStackTrace();
   }
   return pstmt;
 }

 public static void close(Connection conn){
   if(conn == null)return;
   try {
    conn.close();
    conn = null;
   } catch (SQLException e) {
    e.printStackTrace();
   }
 }

 public static void close(Statement stmt){
   try {
    stmt.close();
    stmt = null;
   } catch (SQLException e) {
    e.printStackTrace();
   }
 }

 public static void close(ResultSet rs){
   try {
    rs.close();
    rs = null;
   } catch (SQLException e) {
    e.printStackTrace();
   }
 }
 public String getDbName() {
   return dbName;
 }
 public void setDbName(String dbName) {
   this.dbName = dbName;
 }
 public String getDbServer() {
   return dbServer;
 }
 public String getDbUser() {
   return dbUser;
 }
 public String getDbPwd() {
   return dbPwd;
 }
 public void setDbServer(String dbServer) {
   this.dbServer = dbServer;
 }
 public void setDbUser(String dbUser) {
   this.dbUser = dbUser;
 }
 public void setDbPwd(String dbPwd) {
   this.dbPwd = dbPwd;
 }
 }

=======================================================
2.ParseXML.java

 package com.bn.util;
 import java.util.Properties;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
 import javax.xml.parsers.SAXParserFactory;
 import org.xml.sax.SAXException;
 import java.net.URL;

/**
 * 说明:java读取xml
 * 作者:FH Admin
 * from:fhadmin.cn
 */ 
 public class ParseXML{
     //定义一个Properties 用来存放 dbhost dbuser dbpassword的值 
    private Properties props;
     //这里的props 
     public Properties getProps() {
         return this.props;
     }
     public void parse(String filename) {
         //将我们的解析器对象化 
        ConfigParser handler = new ConfigParser();
         //获取SAX工厂对象 
        SAXParserFactory factory = SAXParserFactory.newInstance();
         factory.setNamespaceAware(false);
         factory.setValidating(false);
         //获取SAX解析
        SAXParser parser=null;
         try {
             parser = factory.newSAXParser();
         } catch (Exception e1) {            
             e1.printStackTrace();
         }        
         URL confURL = null;
         //得到配置文件myenv.xml所在目录. tomcat中是在WEB-INF/classes 
         //下例中BeansConstants是用来存放xml文件中配置信息的类,可以自己代替或定义 
        try{
             confURL = ParseXML.class.getClassLoader().getResource(filename);
 //只需要将我们所需要的XML文件名字输入进去就可以了!
        }catch(Exception e){
             System.out.print(e.toString());
         }
         try
         {    //将解析器和解析对象myenv.xml联系起来,开始解析
            parser.parse(confURL.toString(), handler);
             //获取解析成功后的属性 以后 我们其他应用程序只要调用本程序的props就可以提取出属性名称和值了
            props = handler.getProps();
         }catch(Exception e){
             System.out.println(e.toString());
         }finally{
             factory=null;
             parser=null;
             handler=null;
         }
     }
 }
===================================
3.ConfigParser.java

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

 //使用DefaultHandler的好处 是 不必陈列出所有方法,
public class ConfigParser extends DefaultHandler {
     ////定义一个Properties 用来存放 dbhost dbuser dbpassword的值 
    private Properties props;
     private String currentSet;
     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);
     }
     //在遇到</xxx>结束后,将之前的名称和值一一对应保存在props中 
    public void endElement(String uri, String localName, String qName) throws SAXException {
         props.put(qName.toLowerCase(), currentValue.toString().trim());
     }
 }