【Java】【XML】SAX [3]

SAX サンプル [3]

 SAX を使ったサンプルプログラム(属性と属性値の取得)

サンプル

getDataWithSAX.java

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

public class getDataWithSAX extends DefaultHandler {
	public static void main(String args[]) {
		try {
			getDataWithSAX handler = new getDataWithSAX();
			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 {
		for (int i = 0; i < attr.getLength(); i++) {
			// To Get Names & Values to each attributes
			String attrName = attr.getQName(i);
			System.out.print("Attribute Name : " + attrName);
			String value = attr.getValue(i);
			System.out.println("\t" + value);
		}
		
	}
}

employee.xml(入力ファイル)

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

出力

Attribute Name : name	employee
Attribute Name : id	1
Attribute Name : name	teacher
Attribute Name : id	2