Java XML parsing techniques introduced four

sponsored links
Many xml parsing technology, I do regard the faint call, today concluded a moment, listed here, a total of four categories:
dom, jdom, sax, dom4j
I parse the target file test.xml jdk5.0 environment on the project under the src file.

<?xml version="1.0" encoding="GB2312"?>
<RESULT>
 <VALUE>
  <NO>A1</NO>
  <ADDR> In Sichuan province </ADDR>
 </VALUE>
 <VALUE>
  <NO>B2</NO>
  <ADDR> In Hubei Province </ADDR>
 </VALUE>
</RESULT>


First: dom way
package com.test;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class DomParser {

    public static void main(String arge[]) {
        long lasting = System.currentTimeMillis();
        try {
            File f = new File("src/test.xml");
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(f);
            NodeList nl = doc.getElementsByTagName("VALUE");
            for (int i = 0; i < nl.getLength(); i++) {
                System.out.print(" Number :"
                        + doc.getElementsByTagName("NO").item(i)
                                .getFirstChild().getNodeValue());
                System.out.println(" Address :"
                        + doc.getElementsByTagName("ADDR").item(i)
                                .getFirstChild().getNodeValue());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(" Run time :" + (System.currentTimeMillis() - lasting)
                + "  Ms ");
    }
}

Features: no additional jar package support, based on the tree, you need to load complete a dom structure, easy to use.

The second: sax method
package com.test;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SaxParser extends DefaultHandler {
    java.util.Stack<String> tags = new java.util.Stack<String>();

    public SaxParser() {
        super();
    }

    public static void main(String args[]) {
        long lasting = System.currentTimeMillis();
        try {
            SAXParserFactory sf = SAXParserFactory.newInstance();
            SAXParser sp = sf.newSAXParser();
            SaxParser reader = new SaxParser();
            sp.parse(new InputSource("src/test.xml"), reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(" Run time :" + (System.currentTimeMillis() - lasting)
                + "  Ms ");
    }

    public void characters(char ch[], int start, int length)
            throws SAXException {
        String tag = (String) tags.peek();
        if (tag.equals("NO")) {
            System.out.print(" Number :" + new String(ch, start, length));
        }
        if (tag.equals("ADDR")) {
            System.out.println(" Address :" + new String(ch, start, length));
        }
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attrs) {
        tags.push(qName);
    }

    @Override
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        tags.pop();
    }

}

Features: does not require the introduction of other jar packages, event-based mechanism to save memory footprint, suitable for handling large documents.
Third: jdom way
package com.test;

import java.io.File;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class JdomParser {

    public static void main(String arge[]) {
        long lasting = System.currentTimeMillis();
        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(new File("src/test.xml"));
            Element foo = doc.getRootElement();
            List<Element> allChildren = foo.getChildren();
            for (int i = 0; i < allChildren.size(); i++) {
                System.out.print(" Number :"
                        + allChildren.get(i).getChild("NO").getText());
                System.out.println(" Address :"
                        + allChildren.get(i).getChild("ADDR").getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(" Run time :" + (System.currentTimeMillis() - lasting)
                + "  Ms ");
    }
}

Features: the need for jdom.jar package support, the code less, simple.
Fourth: dom4j way
package com.test;

import java.io.File;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4jParser {

    public static void main(String arge[]) {
        long lasting = System.currentTimeMillis();
        try {
            File f = new File("src/test.xml");
            SAXReader reader = new SAXReader();
            Document doc = reader.read(f);
            Element root = doc.getRootElement();
            Element foo;
            for (Iterator i = root.elementIterator("VALUE"); i.hasNext();) {
                foo = (Element) i.next();
                System.out.print(" Number :" + foo.elementText("NO"));
                System.out.println(" Address :" + foo.elementText("ADDR"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(" Run time :" + (System.currentTimeMillis() - lasting)
                + "  Ms ");
    }
}

Features: dependence dom4j.jar package, easy to use, support the collection processing.

Summary:
JDOM and DOM are two different. First of all, JDOM uses concrete classes rather than just using the interface. This is in some ways simplifies the API, but also limits flexibility. Second, API extensive use of the Collections class to simplify those already familiar with these classes of Java developers use.

DOM JDOM and poor performance in the performance tests. In the small document cases, and should consider using DOM JDOM. In addition, DOM is still a very good choice. DOM implementation is widely used in a variety of programming languages. It or many other XML-related standards based, as it formally W3C Recommendation (non-standard Java-based model of relative), so in certain types of projects may also need it (such as JavaScript using DOM).

SAX performance is better, that depends on its specific analytical method. Detection of a SAX XML stream coming, but not loaded into memory (of course, when the XML stream is read, there will be temporarily hide parts of the document in memory.)

No doubt, DOM4J is the best of these four, the current extensive use of many open source projects DOM4J, such as the famous DOM4J also used to read the Hibernate XML configuration files. If you do not consider the portability, then by DOM4J it!
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Java XML parsing techniques introduced four

  • Hibernate.cfg.xml configuration file (including the primary key generation strategy Introduction)

    Hibernate.cfg.xml configuration file: <? xml version = "1.0" encoding = "utf-8"?> <! DOCTYPE hibernate-configuration PUBLIC "- / / Hibernate / Hibernate Configuration DTD / / EN" "hibernate-configuration-2.0.dtd

  • The EJB3 Persistence

    EJB3 persistence with Hibernate is very similar to the mechanism: Environment: Server: JBOSS5.0 Database: MySQL5.0 1. Set up a data source First of all, in jboss-5.0.0.GA \ server \ default \ deploy, the establishment of a database used to connect the dat

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Servlet brief introduction

    Servlet brief introduction: Servlet is a small application server Are used to complete the B / S architecture, the client requests the response to treatment Platform independence, performance, able to run thread Servlet API for Servlet provides the s ...

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Spring2.0 + hibernate3.1 + log4j + mysql demo

    applicationContext.xml Non-attachment jar package, necessary friends can send an email to todd.liangt @ gmail.com

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries