Parse XML using Java (3)

Source: Internet
Author: User

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)
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;
}

}

}

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.