XML parsing in Java,

XML in the process of developing more and more important, we often need to parse XML documents in the programming. Parsing XML documents in Java in a variety of ways, each approach has its own characteristics. Here we use a different analytical methods by parsing XML documents to demonstrate

First, using DOM (Document Object Model Document Object Model) approach. Parsing XML documents using this method when loading the XML document as a whole, and the formation of the document object tree. All the contents of the document will form a tree of nodes (either elements, attributes or text). So that we can use random read mode for reading. Advantage is that we can use when parsing the document order of the contents of any operation, flexible operation. But the document needs a whole load. So when the contents of the document when the larger of, and we only need to read through of a small part, Xianran yes there Wen Ti's. Therefore, if we read the xml document is relatively small, this approach can be used. This method is relatively simple programming. (Ajax operation XML and Html generally use this method)

Suppose we have the following xml document the existence, name: student.xml, our way of parsing through DOM elements in the document

<?xml version="1.0" encoding="UTF-8"?>

DOM document by parsing the Java code is as follows:

package com.frank.xml;

import java.io.File;
import java.io.IOException;

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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DOMSample {

  * @param args
  * @throws IOException
  * @throws SAXException
 public static void main(String[] args){
  File file=new File("students.xml");
  DocumentBuilderFactory fac=DocumentBuilderFactory.newInstance();
  DocumentBuilder documentBuilder;
  try {
   documentBuilder = fac.newDocumentBuilder();
   Document document=documentBuilder.parse(file);
   NodeList nodeList=document.getElementsByTagName("student");
   for(int i=0;i<nodeList.getLength();i++){
  } catch (Exception e) {
   // TODO Auto-generated catch block

The output is as follows:

Tom === 20 === java
Mike === 23 ===. net

Note that comments section, the same process can be completed parsing the document. Why are child nodes to achieve when the serial number used for the 1,3,5-it? Because each student has a sub-nodes instead of 3 to 7, the text and student text contains (in this blank) is also a child node.

For XML parsing using SAX

Parsing XML with SAX is the order of nature. Is the top-down parsing XML documents. Event-driven mechanism is adopted. When faced with a node when processing immediately, not wait until the whole document loaded handle. SAX parsing provided by the use of a number of ways. When faced with a certain part of the document, the use of callback mechanism call the appropriate methods for proper handling. For example, SAX methods to manipulate a node exists: startElement and endElement

When faced with a start node calls startElement, after the end of node encounters a call to endElement. We can write these two methods to realize the specific process of parsing XML documents, read the content provided by using a method other characters

There is also time to start parsing the document and the document calls the startDocument call endDocument end analysis

The overall load without using SAX parsing the document, so the larger the document analysis is more suitable when using SAX approach. Analysis of speed and better than DOM, but the operation code will take some work.

Similarly, we resolve just students.xml, use of SAX, can be as follows:

package com.frank.xml;

import java.util.Stack;

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 SAXSample extends DefaultHandler {
 Stack tags = new Stack();
  * @param args
 public static void main(String[] args) {
   SAXParserFactory factory=SAXParserFactory.newInstance();
   SAXParser sAXParser=factory.newSAXParser();
   SAXSample sAXSample=new SAXSample();
   sAXParser.parse(new InputSource("students.xml"), sAXSample);
  }catch(Exception ex){


 public void characters(char ch[], int start, int length)
   throws SAXException {
  // TODO Auto-generated method stub
  String tag = (String) tags.peek();
   System.out.println("name="+new String(ch, start, length));
   System.out.println("age="+new String(ch, start, length));
   System.out.println("skill="+new String(ch,start,length));

 public void endElement(String arg0, String arg1, String arg2)
   throws SAXException {
  // TODO Auto-generated method stub

 public void startElement(String uri,String localName,String qName,Attributes attrs)  throws SAXException {
  // TODO Auto-generated method stub

The results are:

name = Tom
age = 20
skill = java
name = Mike
age = 23
skill =. net

分类:Java 时间:2010-04-11 人气:346
blog comments powered by Disqus


  • Java programming language commonly used in the method of updating XML documents 2010-09-28

    Quoted from http://www.ibm.com/developerworks/cn/java/l-javaxml/ This paper briefly discusses the Java programming language update XML documents in the four commonly used methods, and analysis of the merits of the four methods. Secondly, the article

  • JAVA several analytical methods for XML 2010-04-05

    XML description for a more comprehensive or IBM's column: http://www.ibm.com/developerworks/cn/xml/theme/x-java.html Basically covers all aspects of JAVA with XML 1. Introduction 1) DOM (JAXP Crimson parser) DOM is platform-and language-independent m

  • Java parsing XML documents (2): sax read xml file export excel 2010-03-22

    1. Concept SAX (Simple API for XML), event-based XML Simple API, parsing XML documents is one of the two API. 2. Sax parsing 1. Use to the package: javax.xml.parsers: parser factory tools org.xml.sax: provides the core SAX API For example: import jav

  • Java parsing XML documents four methods 2010-05-07

    1) DOM (JAXP Crimson parser) DOM is platform-and language-independent manner, said the official W3C standard XML document. DOM is a hierarchical organization of nodes or pieces of information collection. This hierarchy allows the developer to find sp

  • java parsing of XML documents. nodes increases. deletions Summary 2010-10-11

    package test; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.trans

  • [Reprinted] JAVA on reading and writing XML documents 2010-09-25

    There are many ways to read and write XML ~ ~ JAVA in a rich class of the XML file at ~ ~ such XMLReader .... JDOM ... DOM and so on ~ ~ Here is what I found from online information and examples of successful pilot ~ ~ Using the DOM ~ ~ ~ do not need

  • DOM4J on XML documents to read and write operations such as additions and deletions to change 2010-03-16

    XML documents with DOM4J on CRUD operations such as reading and writing is my own exercises, and notes there is no order and only later see use. Main method in the constructor to do the simple instructions, involved XML, XSD, DTD document is no longe

  • Using dom4j to create, edit XML documents and format the output and the Chinese to solve the problem 2010-08-22

    package com.holen.dom4j; import java.io.File; import java.io.FileWriter; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.do

  • Android parse XML documents using PULL 2010-12-14

    Android PULL technical analysis used in the system than using SAX XML documents much better technical performance. Android developers proposed technical parsing XML documents using PULL. SAX with similar, but the return type of event PULL technology

  • XML documents using Libxml2 operation 2010-02-25

    1, Libxml2 Description: Libxml2 is an xml parser c-language version, was originally a tool for the Gnome project development, based on the MIT License is a free open source software. It addition to supporting the c-language version, it also supports

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 闽ICP备15018612号

processed in 0.033 (s). 11 q(s)