The Java SAX Parser parses xml configuration files.

Source: Internet
Author: User

The Java SAX Parser parses xml configuration files.

Recently, Tl asked me to do the technical accumulation of the company's projects. Today, let me finish parsing the xml configuration file with the SAX Parser. I have been working on a. Net project. Recently, I just transferred it to the Java group. I think. Is TL waiting for me. I am happy to have a spare time .. Net parsing XML, It is very comfortable. It takes three or two times. I always think there is no fundamental difference between Java and. net. So. I will do it without delay. First, I went online and googled a lot of articles. I am happy. But after 10 minutes, I was depressed. Almost all of them are the same. And I have called it for a long time, but I have not called it out. So I decided to write it myself. Believe in others, it is better to trust yourself. After some hard work, we finally got it done. Let's share it. The Code is as follows:

/*
* Read the configuration information from the XML file and return the database connection through the configuration information.
*
*/
Package com. augow. xmlconfigreader;

Import org. xml. Sax. attributes;
Import org. xml. Sax. helpers. defaulthandler;
Import org. xml. Sax. saxexception;
Import java. util. properties;

/*
* The parser used to parse XML files using the sax Method
*/

Public class configparser extends defaulthandler
{
/* Props: used to store the attributes of the nodes parsed by the parser and corresponding to the nodes. It is a hash table.
* Currentname: name of the current node
* Currentvalue: used to store the attribute values corresponding to the current node.
*/
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;
}


/*
* Read the value XXX in <XXX> and pay it to QNAME. The notification parser parses the value corresponding to the current node. At the same time, the currentvalue buffer is cleared to save the attribute value corresponding to the current 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)
Throws saxexception
{
Currentvalue. Delete (0, currentvalue. Length ());
This. currentname = QNAME;
}


/* Read the attribute values between <XXX> </xxx> and save them as characters to the CH array, and record the corresponding length to ensure
* The length is the length of a whole character, and the content in the character array is added to the currentvalue buffer according to the length.
* After each XML file is read, only the resolved value is saved in CH, and only the unique value corresponding to the current node is saved in currentvalue.
*/
Public void characters (char [] CH, int start, int length)
Throws saxexception
{
Currentvalue. append (CH, start, length );
}


/* When </xxx> is encountered, save the current QNAME and the value in the currentvalue buffer corresponding to QNAME to the hash table props for external programs to call.
* @ 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 ());
}

 

}

/*
* Read the configuration information from the XML file and return the database connection through the configuration information.
*
*/

Package com. augow. xmlconfigreader;

Import java. util. properties;
Import java.net. url;
Import javax. xml. parsers. saxparser;
Import javax. xml. parsers. saxparserfactory;

/*
* It is used to instantiate the parser, parse the XML file using the parser, return the parsing result, and obtain the result through the provided
* Methods are called by external programs.
*/
Public class xmlreader
{
// Hash table used to store resolution results
Private Properties props;

Public xmlreader (string filename)
{
Try
{
Parse (filename );
}
Catch (exception E)
{
E. printstacktrace ();
}
}

Public properties getprops ()
{
Return this. Props;
}


/*
* Method for analyzing XML files
*/
Public void parse (string filename)
Throws exception
{
// Instantiate the parser
Configparser handler = new configparser ();

// Instantiate the factory for analysis
Saxparserfactory factory = saxparserfactory. newinstance ();

// Instantiate the analysis class
Saxparser parser = factory. newsaxparser ();

// Obtain the path corresponding to the XML file
URL confurl = xmlreader. Class. getclassloader (). getresource (filename );
Try
{
Parser. parse (confurl. tostring (), Handler );
Props = handler. getprpos ();
}
Finally
{
/*
* Destroy expired objects
*/
Factory = NULL;
Parser = NULL;
Handler = NULL;
}

}


/*
* The method provided for external programs to call for returning the XML file attributes required by the program
*/
Public String getelementvalue (string elementname)
{
// Elementvalue: attribute value of the node corresponding to elementname
String elementvalue = NULL;
Elementvalue = props. getproperty (elementname );
Return elementvalue;
}
}

 

/*
* Read the configuration information from the XML file and return the database connection through the configuration information.
*
*/
Package com. augow. xmlconfigreader;

Import java. SQL .*;

/*
* Used to create and return the database connection configured by the specified xml configuration file
*/
Public class dbconnection
{
Private Static connection conn = NULL;
Public dbconnection (){}
/*
* Create a specified database connection
*/
Public static connection createconnection ()
{
Xmlreader P = new xmlreader ("xmlconfigure. xml ");
Try
{
/*
* Add the JDBC driver package
*/
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;
}

}

}

/*
* Read the configuration information from the XML file and return the database connection through the configuration information.
*
*/
Package com. augow. xmlconfigreader;
Import java. SQL .*;

/*
* Used for testing
*/
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 ();
Rs1_stat.exe cutequery ("select sname from student where snum = '000000 '");
While (Rs. Next ())
{
System. Out. println (Rs. getstring ("sname "));

}
Con. Close ();
}
Catch (exception E)
{
E. printstacktrace ();
}

}

}

I connected to the database, and the test class came up with a brain, hoping to help those who needed it ~~~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.