【Java】【XML】SAX [1]

SAXプログラミング手順 / SAX programming Procedures

 [1] Create Event Handler
    => myHandler handler = new myHandler();
 [2] Create SAX parser
    => SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
 [3] Call Parser and set Event Handler. (And then SAX parser can call methods on the Event Handler)
    => parser.parse(".\\src\\employee.xml", handler);
 [4] Parser Handling
 [5] Event Handler Processing(startDocument/startElement etc...)

サンプル

 XMLファイルの要素数を数えるプログラム

countElemntNum.java

import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class countElemntNum extends DefaultHandler {
	int count = 0;
	public static void main(String args[]) {
		try {
			countElemntNum handler = new countElemntNum();
			SAXParserFactory saxFact = SAXParserFactory.newInstance();
			SAXParser parser = saxFact.newSAXParser();
			parser.parse(".\\src\\employee.xml", handler);
		} catch (Exception ex) {
			System.out.println(ex); 
			System.out.println("Parser not support" );
		}
	}
	
	public void startDocument() throws SAXException {
		
	}
	
	public void startElement(String namespaceURI, String localName,
			String qualifiedName, Attributes attr) throws SAXException {
		System.out.println("Element name is " + qualifiedName);
		count++;
	}
	
	public void endDocument() throws SAXException {
		System.out.println("Total Number of Elements are " + count);
	}
}

employee.xml(入力ファイル)

<?xml version="1.0"?>
<employee-detail>
	<employee>
		<Name>test1</Name>
		<id>test2</id>
		<email>____xxx____@xxx.com</email>
	</employee>
</employee-detail>

出力

Element name is employee-detail
Element name is employee
Element name is Name
Element name is id
Element name is email
Total Number of Elements are 5