Java reads and processes XML configuration files

Source: Internet
Author: User

Java and XML are a combination of gold. Many articles on the Internet have introduced that XML, as a data exchange in e-commerce, has become irreplaceable. However, during system development, we may not all use data exchange. Is it impossible to use XML?

Of course not. Now there is a new trend. The configuration files of java programs start to use the XML format. In the past, they used the INI format similar to windows. (classes such as Propertiesy are also used in Java to process such attribute configuration files ). using XML as a Java configuration file has many advantages. From the Tomcat installation configuration file and the J2ee configuration file, we have seen that XML is widely used, let us also follow the popular trend and arm it with XML.

Now the key is how to read the XML configuration file? There are several types of XML Parser: Mainly DOM and SAX. These differences are described in many online articles.

In the XML project team of apache, there are currently Xerces Xalan Cocoon projects that develop XML-related technologies. Tomcat itself uses Sun's JAXP, and its XSL Taglib project uses the Xerces parser.

Well, the above are all annoying theoretical issues. Please read the XML configuration file as soon as possible.

In our program, there are usually some variables determined according to the host environment. for example, the database access user name and password may be set differently on different hosts. you only need to change the XML configuration file to run properly.

Localhost

Sqlname

Username

Password

The above myenv. xml configuration file is generally placed in the tomcat WEB-INF/classes directory.

We compile a Java program to directly read and extract the dbhost dbuser dbpassword for other programs to access the database.

Currently, there are many methods of using SAX. The main difference with DOM is that it reads XML files in a row for analysis. It is suitable for large files. DOM is a one-time read into the memory and obviously cannot deal with large files. here we use SAX parsing. Due to the continuous development of the SAX Parser, many articles on the Internet are aimed at the old version. if you use JDK1.4, you can refer to the article about processing XML documents with SAX. the program here is developed based on its improvements and after practical debugging.

Java program read from myenv. xml above:

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 do not have to display all the methods,

Public class ConfigParser extends DefaultHandler {

/// Define a Properties to store the value of dbhost dbuser dbpassword

Private Properties props;

Private String currentSet;

Private String currentName;

Private StringBuffer currentValue = new StringBuffer ();

// The Builder initializes props.

Public ConfigParser (){

This. props = new Properties ();

}

Public Properties getProps (){

Return this. props;

}

// Define the method for starting element parsing. Here, the name xxx is extracted.

Public void startElement (String uri, String localName, String qName, Attributes attributes)

Throws SAXException {

CurrentValue. delete (0, currentValue. length ());

This. currentName = qName;

}

// Add the value to currentValue

Public void characters (char [] ch, int start, int length) throws SAXException {

CurrentValue. append (ch, start, length );

}

// Save the previous names and values in props one by one after the end

Public void endElement (String uri, String localName, String qName) throws SAXException {

Props. put (qName. toLowerCase (), currentValue. toString (). trim ());

}

}

Is the above parsing procedure relatively simple? In fact, parsing XML is so simple.

Now we have extracted the value of dbhost dbuser dbpassword from localhost sqlname username password. However, this is only in the parser and our program cannot be accessed. We need to compile another program.

Import java. util. Properties;

Import javax. xml. parsers. SAXParser;

Import javax. xml. parsers. SAXParserFactory;

Import java.net. URL;

Public class ParseXML {

// Define a Properties to store the value of dbhost dbuser dbpassword

Private Properties props;

// The props here

Public Properties getProps (){

Return this. props;

}

Public void parse (String filename) throws Exception {

// Visualize our parser

ConfigParser handler = new ConfigParser ();

// Obtain the SAX factory object

SAXParserFactory factory = SAXParserFactory. newInstance ();

Factory. setNamespaceAware (false );

Factory. setValidating (false );

// Obtain the SAX Parsing

SAXParser parser = factory. newSAXParser ();

// Get the configuration file myenv. xml directory. tomcat is in WEB-INF/classes

// In the following example, BeansConstants is a class used to store configuration information in xml files. You can replace or define it yourself.

URL confURL = BeansConstants. class. getClassLoader (). getResource (filename );

Try

{

// Associate the parser with the parsing object myenv. xml to start parsing.

Parser. parse (confURL. toString (), handler );

// After obtaining the parsed attributes, other applications can extract the attribute names and values by calling the props of this program.

Props = handler. getProps ();

} Finally {

Factory = null;

Parser = null;

Handler = null;

}

}

}

Because our XML file is the simplest form, the parser is relatively simple, but this is enough to deal with our configuration file.


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.