Skip to content

Instantly share code, notes, and snippets.

@ts-3156
Created May 16, 2011 08:57
Show Gist options
  • Save ts-3156/974116 to your computer and use it in GitHub Desktop.
Save ts-3156/974116 to your computer and use it in GitHub Desktop.
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
*
*「XMLファイルの読み込みってめんどーだよねー」っていう趣旨でこのコードを書いたんですが、
*意外に短く書けたので拍子抜けしてしまいました。それでも、似たような名前のメソッドが多くてうんざりですが…。
*
*やっぱり、スクリプト言語派の人からしたら、たったこれだけの目的のために
*こんな長いコードを書くのは論外だったりするんですかねー?
*
*ちなみに、ちゃんとテストしてないので、意図通りに動かない可能性大です。
*
*このファイルをGistにアップロードしたのはhttp://twitter.com/ts_3156ですが、
*大枠はarc@dmzさん(http://digitalmuseum.jp/user/arc/)が公開しているものを元にしています。
*便利なものを作ってくださってありがとうございます。改変して公開することが問題だったら誰か教えてください…!
*
*/
public class ConfigFile {
private String fileName;
private Document doc;
public ConfigFile(String fileName) {
this.fileName = fileName;
load(new File(fileName));
}
public void load(File file) {
try {
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbfactory.newDocumentBuilder();
doc = builder.parse(file);
} catch (Exception e) {
System.err.println("設定ファイル(" + file.getName() + ")を読めませんでした。");
return;
}
}
/**
* このメソッドを作るためにこのクラスを作りました。
* 本当は例外処理とかが必要です。
* @param tagName
* @param attrName
* @return
*/
public int getAttrValue(String tagName, String attrName){
return new Integer(getNodeByTagName(tagName).getAttributes().getNamedItem(attrName).getNodeValue());
}
/**
* タグ名でNodeを取得します。
* 同じ名前のタグが複数あっても、最初に見つかったタグしか返さないです。
* @param tagName
* @return
*/
public Node getNodeByTagName(String tagName) {
Node n = null;
try {
NodeList list = doc.getElementsByTagName(tagName);
n = list.item(0);
} catch (Exception e) {
return null;
}
return n;
}
/**
* XMLのめんどくささを再現するために作りました。
* 親要素、子要素のタグ名からNodeを取得します。
* 似たような名前のメソッドが多くてうんざりしませんか…?
*
* @param tagName
* @param childTagName
* @return
*/
public Node getNodeByChildName(String tagName, String childTagName) {
Node nodeToReturn = null;
try {
NodeList parentNodeList = doc.getElementsByTagName(tagName);
int i = 0;
Node node = null;
while ((node = parentNodeList.item(i++)) != null) {
if (node.getNodeType() == Node.ELEMENT_NODE){
Node childNode = getChildNodeByTagName("name", node);
if(childNode != null && childNode.getTextContent().equals(childTagName)){
nodeToReturn = node;
break;
}
}
}
} catch (Exception e) {
return null;
}
return nodeToReturn;
}
public Node getChildNodeByTagName(String str, Node node) {
if (node == null) return null;
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i ++) {
Node n = list.item(i);
if (n.getNodeName().equals(str)) return n;
}
return null;
}
public String getName() { return fileName; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment