Read processing of XML configuration files

Source: Internet
Author: User
Tags format ini tostring tomcat stringbuffer
Read processing of XML XML configuration files
Banqiao Man jdon.com 2002/2

Java and XML is a combination of gold, there are many articles on the Internet, XML as a data exchange in E-commerce, has its irreplaceable role, but in peacetime system development, we do not necessarily have to use data exchange, is not the use of XML?

Of course not, now there is a new trend, the Java program's configuration files are beginning to use XML format, used to be similar to the Windows INI format. (There are also classes in Java that specifically deal with such property profiles). There are many benefits to using XML as a Java configuration file, and we've seen the universal application of XML from the Tomcat installation profile and the EE configuration file, Let's also be armed with XML to follow popular trends.

Now the key is how to read the XML configuration file? There are several XML parsers: the main DOM and sax, these differences are described in the online article a lot.

In the Apache XML Project group, there are currently xerces Xalan Cocoon several XML-related technologies Project.tomcat themselves using Sun JAXP, and the Taglib parser is used in its XSL Xerces project.

OK, all of these are annoying theoretical issues, or quickly cut into the XML configuration file read it.

In our program, there are usually some variables that are determined according to the host environment. For example, database access username and password, different hosts may be set differently. You can run it as long as you change the XML configuration file.

<myenv>

<datasource>
<dbhost>localhost</dbhost>
<dbname>sqlname</dbname>
<dbuser>username</dbuser>
<dbpassword>password</dbpassword>
</datasource>

</myenv>






The above myenv.xml configuration file is typically placed under Tomcat's web-inf/classes directory.

We compiled a Java program to read directly, Dbhost Dbuser Dbpassword extracted for other programs to access the database.

Currently using Sax is much more, the main difference with DOM is that sax is a row to read XML files for analysis, suitable for larger files, Dom is a one-time read into memory, obviously can not deal with large files. Here we use Sax parsing, because the SAX parser is evolving, There are a number of articles on the web that are aimed at older versions. If you use JDK1.4, you can refer to the article using sax to work with XML documents. The program here is based on its improvement and has been debugged in practice.

Java program to read above myenv.xml:

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
public class Configparser extends DefaultHandler {

Defines the value of a properties used to store Dbhost dbuser Dbpassword
Private Properties props;

Private String Currentset;
Private String Currentname;
Private StringBuffer CurrentValue = new StringBuffer ();

Builder Initialization Props
Public Configparser () {

This.props = new Properties ();
}

Public Properties GetProps () {
return this.props;
}

Defines a method that begins parsing an element. This is to extract the name xxx in <xxx>.
public void Startelement (string uri, String localname, String qName, Attributes Attributes)
Throws Saxexception {
Currentvalue.delete (0, Currentvalue.length ());
This.currentname =qname;

}

This 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 you encounter the </xxx> end, save the previous name and value one by one in props

public void EndElement (string uri, String localname, String qName) throws Saxexception {

Props.put (Qname.tolowercase (), currentvalue.tostring (). Trim ());
}

}


Is this parser simpler? In fact parsing XML is so simple.

Now we have extracted the value of Dbhost dbuser dbpassword localhost sqlname username password. But this is only within the parser, our program is not accessible. A program needs to be compiled.



Import java.util.Properties;
Import Javax.xml.parsers.SAXParser;
Import Javax.xml.parsers.SAXParserFactory;
Import Java.net.URL;

public class parsexml{

Defines the value of a properties used to store Dbhost dbuser Dbpassword
Private Properties props;

Here's the props.
Public Properties GetProps () {
return this.props;
}

public void Parse (String filename) throws Exception {

The object of our parser
Configparser handler = new Configparser ();

Get Sax Factory Objects
SAXParserFactory factory = Saxparserfactory.newinstance ();
Factory.setnamespaceaware (FALSE);
Factory.setvalidating (FALSE);

Get Sax parsing
SAXParser parser = Factory.newsaxparser ();

Get the directory where the configuration file myenv.xml. Tomcat is in web-inf/classes.
In the following example, Beansconstants is a class that holds configuration information in an XML file and can be used to replace or define
URL Confurl = BeansConstants.class.getClassLoader (). getresource (filename);

Try
{
Connect the parser to the parsing object Myenv.xml and start parsing
Parser.parse (Confurl.tostring (), handler);
After the successfully parsed property is obtained, our other applications can extract the attribute name and value as long as the props of this program is invoked.
Props = Handler.getprops ();
}finally{
Factory=null;
Parser=null;
Handler=null;
}

}

}


Because our XML file is in the simplest form, the parser is relatively simple, but that's enough to deal with our configuration file.

To judge the advancement of a program system, let's take a look at his profile, and if you're using the old xxx=123 file like. ini,
We may be a little smile, he is outdated ...


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.