【Java】【XML】DOM [2]

DOM サンプル [2]

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

サンプル

retrieveData.java

import javax.xml.parsers.*;
import org.w3c.dom.*;

/* U can retrieve the data in this example */
public class retrieveData {
	public static void main(String args[]) {
		try {
			// To Create a factory
			DocumentBuilderFactory factory =
				DocumentBuilderFactory.newInstance();
			// Use the factory to create a builder
			DocumentBuilder builder =
				factory.newDocumentBuilder();
			Document doc = builder.parse(".\\src\\employee.xml" );
			// To get a list of all elements in the document
			NodeList list = doc.getElementsByTagName("*" );
			
			// Output
			System.out.println("XML Elements : " );
			for (int i = 0; i < list.getLength(); i++) {
				Element element = (Element)list.item(i);
				System.out.println(element.getNodeName());
			}
		} catch (Exception ex) {
			System.out.println(ex);
			System.out.println("Parser not support" );
		}
	}
}

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>

出力

XML Elements : 
employee-detail
employee
Name
id
email
employee
Name
id
email