【Java】【XML】SAX [2]

SAX サンプル [2]

 SAX を使ったサンプルプログラム

サンプル

saxDemo.java

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

public class saxDemo extends DefaultHandler {
	boolean id = false;
	boolean names = false;
	boolean email = false;
	
	public static void main(String args[]) {
		try {
			saxDemo handler = new saxDemo();
			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 startElement(String namespaceURI, String localName,
			String qualifiedName, Attributes attr) throws SAXException {
		if (qualifiedName.equals("id" )) {
			id = true;
		}
		if (qualifiedName.equals("Name" )) {
			names = true;
		}
		if (qualifiedName.equals("email" )) {
			email = true;
		}
	}
	
	public void characters(char ch[], int start, int length)
		throws SAXException {
		String str = new String(ch, start, length);
		
		if (id) {
			System.out.println("ID : " + str);
			id = false;
		}
		if (names) {
			System.out.println("Name : " + str);
			names = false;
		}
		if (email) {
			System.out.println("E-mail : " + str);
			email = false;
		}
	}
}

employee.xml(入力ファイル)

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

出力

Name : test1
ID : id1
E-mail : ____xxx____1@xxx.com
Name : test2
ID : id2
E-mail : ____xxx____2@xxx.com