XML parsing in Java,

sponsored links
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"?>
<students>
 <student>
  <name>Tom</name>
  <age>20</age>
  <skill>java</skill>
 </student>
 <student>
  <name>Mike</name>
  <age>23</age>
  <skill>.net</skill>
 </student>
</students>

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++){
    //System.out.print(document.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
    //System.out.print("===");
    //System.out.print(document.getElementsByTagName("age").item(i).getFirstChild().getNodeValue());
    //System.out.print("===");
    //System.out.print(document.getElementsByTagName("skill").item(i).getFirstChild().getNodeValue());
    System.out.print(nodeList.item(i).getChildNodes().item(1).getFirstChild().getNodeValue());
    System.out.print("===");
    System.out.print(nodeList.item(i).getChildNodes().item(3).getFirstChild().getNodeValue());
    System.out.print("===");
    System.out.print(nodeList.item(i).getChildNodes().item(5).getFirstChild().getNodeValue());
    System.out.println("");
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

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) {
  try{
   SAXParserFactory factory=SAXParserFactory.newInstance();
   SAXParser sAXParser=factory.newSAXParser();
   SAXSample sAXSample=new SAXSample();
   sAXParser.parse(new InputSource("students.xml"), sAXSample);
  }catch(Exception ex){
   ex.printStackTrace();
  }

 }

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

 @Override
 public void endElement(String arg0, String arg1, String arg2)
   throws SAXException {
  // TODO Auto-generated method stub
  tags.pop();
 }

 @Override
 public void startElement(String uri,String localName,String qName,Attributes attrs)  throws SAXException {
  // TODO Auto-generated method stub
  tags.push(qName);
 }
}

The results are:

name = Tom
age = 20
skill = java
name = Mike
age = 23
skill =. net
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of XML parsing in Java,

  • 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

  • Based on JDBC, JPA Annotation achieve simple CRUD Generic Dao

    The origin of ideas are pretty long history of reasons: [Use iBATIS history] The use of iBATIS has been a long time, the system is to use the CRUD template tool to generate the code, although there are tools to generate, but looked at a lot of CRUD the Sq

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