次のようなXMLファイルを読んで、内容を表示するプログラムを示します。
XMLファイルをパースして、DOMツリーを生成後、ドキュメントより各要素を操作して表示します。
<?xml version="1.0" encoding="UTF-8"?> <サイト> <title>XMLの学習</title> <page id="12"> <title>基礎編</title> <file>基礎編.html</file> </page> <page id="89"> <title>応用編</title> <file>応用編.html</file> </page> </サイト>
目標の実行結果です。
ルート要素のタグ名:サイト ID:12 タイトル:基礎編 ファイル:基礎編.html ID:89 タイトル:応用編 ファイル:応用編.html
次のステップの処理です。
以下にこのソースプログラムをしまします。
import java.io.File;
//XMLファイルをパースしてDOMツリー取得に必要なインポート
import javax.xml.parsers.DocumentBuilderFactory;//下記DocumentBuilder生成用
import javax.xml.parsers.DocumentBuilder;//DOM オブジェクトツリーをパースする
//ドキュメントと要素操作に必要なインポート
import org.w3c.dom.Document;//Documentは、XML文書のツリー全体を表すクラス
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* XMLファイルをパースして、DOMツリーを生成後、ドキュメントより各要素を操作して表示する。
*
*/
public class XmlLoadTest {
public static void main(String []s){
try {
//DOM オブジェクトツリーをパースするインスタンスを生成するDocumentBuilderオブジェクトを生成
DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbfactory.newDocumentBuilder();
// パースを実行してDocumentオブジェクトを取得
Document document = builder.parse(new File("test.xml"));
// ルート要素を取得(タグ名:site)
Element rootElement = document.getDocumentElement();
System.out.println("ルート要素のタグ名:" + rootElement.getTagName());
// nodeListの子孫となる "page" の名前の要素すべてを NodeListのインスタンスとして取得
NodeList nodeList = rootElement.getElementsByTagName("page");
// page要素の数だけループ
for (int i=0; i < nodeList.getLength() ; i++) {
// page要素を取得
Element elementPange = (Element)nodeList.item(i);
// id属性の値を取得
String id = elementPange.getAttribute("id");
// page要素からtitle要素のリストの先頭要素から子ノード値のタイトルを取得
NodeList titleList = elementPange.getElementsByTagName("title");
Element titleElement = (Element)titleList.item(0);
String title = titleElement.getFirstChild().getNodeValue();
// file要素のリストを取得
NodeList fileList = elementPange.getElementsByTagName("file");
// file要素を取得
Element fileElement = (Element)fileList.item(0);
// file要素の最初の子ノード(テキストノード)の値を取得
String file = fileElement.getFirstChild().getNodeValue();
System.out.println("ID:" + id + " " +
"タイトル:" + title + " " +
"ファイル:" + file);
}
}
catch (Exception e){
System.out.println(e.toString());
}
}
}