ミッションたぶんPossible

どこにでもいるシステムエンジニアのなんでもない日記です。たぶん。

JavaでXML読込

 今、Cassandraでログを蓄積しておく仕組みを実装しています。Cassandraの設定をXMLで外に出す必要があったのですが、久々にやったらすっかり忘れてたので…。

 という訳で備忘録的にXMLファイル読み込みをJavaで行う方法を残しておこうと思います。

XMLReadTest.java
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.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class XMLReadTest {

	public static String serverName;
	public static int port;
	public static String keyspace;

	public static void main(String[] X) {

		readPropertyFile("TrackLogProperty.xml");

		System.out.println("serverName = " + serverName);
		System.out.println("port = " + port);
		System.out.println("keyspace = " + keyspace);

	}

	/*
	 * プロパティファイル(XML)を読み込む。
	 *
	 * @param filename
	 */
	private static void readPropertyFile(String filename) {

		File file;
		DocumentBuilderFactory factory;
		DocumentBuilder builder;
		Document doc;

		try {

			file = new File(filename);
			factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();
			doc = builder.parse(file);

		} catch(ParserConfigurationException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException();
		} catch (SAXException e) {
			throw new RuntimeException();
		}

		// パース開始
		NodeList childs = doc.getChildNodes();

		for(int i = 0; i < childs.getLength(); i++) {
			Node n = childs.item(i);
			Element e = (Element)n;

			if(e.getNodeType() != Node.ELEMENT_NODE) continue;

			// プロパティ
			if(!"property".equals(e.getTagName())) continue;

			// プロパティの子要素
			NodeList paramNode = n.getChildNodes();
			for(int j = 0; j < paramNode.getLength(); j++) {
				Node n2 = (Node)paramNode.item(j);

				if(n2.getNodeType() != Node.ELEMENT_NODE) continue;

				// サーバ名
				if("servername".equals(n2.getNodeName())) {

					serverName = n2.getFirstChild().getNodeValue();
				// ポート番号
				} else if("port".equals(n2.getNodeName())) {

					port = Integer.parseInt(n2.getFirstChild().getNodeValue());

				// キースペース
				} else if("keyspace".equals(n2.getNodeName())) {

					keyspace = n2.getFirstChild().getNodeValue();
				}
			}

		}
	}
}
CassandraProperty.xml(プロパティファイル)
<?xml version="1.0" encoding="UTF-8"?>
<property>
  <servername>localhost</servername>
  <port>9160</port>
  <keyspace>Keyspace01</keyspace>
</property>


 サーバ名とポート番号、あとCassandraでDB名にあたるKeyspace名をXMLで持ち、それをJavaで読み込むという簡単な実装です。

 …こういうなんでも無いもので時間かかったりするとホントにウンザリしますね。でも一システムで一回くらいしか実装しないから暗記出来るほど書けるわけでもないし。
 次回からはこれ見てすんなりクリアしたいものです。