How Java reads XML

Time:2022-5-26

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 Webpage GameProject fhadmin org
public void readXML(){

SAXReader sr = new SAXReader();// Gets the object that reads 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();

}//Get the location of the XML. Then start reading. And put the data into doc

Element el_ root = doc. getRootElement();// Fetch data from the outside to get the root node of XML.
Iterator it = el_ root. elementIterator();// Traverse successively from the root node to obtain all child nodes under the root node

 While (it. Hasnext()) {// traverse the child node
 
  Object o = it. next();// Then obtain the child nodes under the child node
 Element el_row = (Element)o;
  String s = el_row.getText();
  Iterator it_row = el_row.elementIterator();
  int i =1;
  While (it_row. Hasnext()) {// traverse nodes
  Element el_ ename = (Element)it_ row. next();// Get all page tour data under this node.

   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.www.pizei.comprintln(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 project fhadmin org
public class ParseXML{

//Define a property to store the value of dbhost, dbuser and dbpassword
private Properties props;
 //Props here
 public Properties getProps() {
     return this.props;
 }
 public void parse(String filename) {
     //Objectify our parser
    ConfigParser handler = new ConfigParser();
     //Get Sax factory object
    SAXParserFactory factory = SAXParserFactory.newInstance();
     factory.setNamespaceAware(false);
     factory.setValidating(false);
     //Get Sax resolution
    SAXParser parser=null;
     try {
         parser = factory.newSAXParser();
     } catch (Exception e1) {            
         e1.printStackTrace();
     }        
     URL confURL = null;
     //Get the configuration file myenv XML directory Tomcat is in WEB-INF / classes
     //In the following example, beansconstants is a class used to store the configuration information in the XML file, which can be replaced or defined by yourself
    try{
         confURL = ParseXML.class.getClassLoader().getResource(filename);

//Just enter the name of the XML file we need!

}catch(Exception e){
         System.out.print(e.toString());
     }
     try
     {// connect the parser with the parsing object myenv.xml to start parsing
        parser.parse(confURL.toString(), handler);
         //After obtaining the successfully resolved attribute, our other applications can extract the attribute name and value by calling props of this program
        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;
//The advantage of using defaulthandler is that you don’t have to display all the methods,
//Java project fhadmin org
public class ConfigParser extends DefaultHandler {

////Define a property to store the value of dbhost, dbuser and dbpassword
private Properties props;
 private String currentSet;
 private String currentName;
 private StringBuffer currentValue = new StringBuffer();
 //Builder initializes props
 public ConfigParser() {
     this.props = new Properties();
 }
 public Properties getProps() {
     return this.props;
 }
 //Defines a method to start parsing elements Here is the name XXX extracted from < XXX >
 public void startElement(String uri, String localName, String qName, Attributes attributes)throws SAXException {
     currentValue.delete(0, currentValue.length());
     this.currentName =qName;
 }
 //Here is to add the value between < XXX > < / xxx > to currentvalue
 public void characters(char[] ch, int start, int length) throws SAXException {
     currentValue.append(ch, start, length);
 }
 //After encountering < / xxx >, save the previous names and values in props one by one
public void endElement(String uri, String localName, String qName) throws SAXException {
     props.put(qName.toLowerCase(), currentValue.toString().trim());
 }

}