@634

634 - JAXP - DOM - 指定した要素を取得

Advertisement

Element

要素名を指定して内容を取得するためには、getElementsByTagNameメソッドを利用します。XMLドキュメントのツリーを順に読む必要がないので処理を簡単に記述することができます。以下に利用例を示します。
import java.io.BufferedInputStream;
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DOMTest {

    public static void main(String[] args) {
        try{
            FileInputStream fis = new FileInputStream("./sample.xml");
            BufferedInputStream bis = new BufferedInputStream(fis);

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(bis);

            // ルート要素の取得
            Element root = doc.getDocumentElement();

            // book 要素のリストを作成
            NodeList list = root.getElementsByTagName("book");

            // 1つ目の要素を表示
            System.out.println("1つ目のbook 要素" + list.item(0));

        }catch(Exception e){
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}

入力ファイル(sample.xml)
<?xml version="1.0" encoding="Shift_JIS"?>
<document>
    <book id="10">
        <title>AAA</title>
        <price>1500</price>
    </book>
    <book id="20">
        <title>BBB</title>
        <price>1200</price>
    </book>
</document>

結果
<book id="10">
    <title>AAA</title>
    <price>1500</price>
</book>

Advertisement

ショートカット

634
634ブログ
このカテゴリのトップページに戻る
Incubator(Pukiwiki)
634ラボ
   UIコレクションギャラリー
   ZO-3ジェネレーター

サイト検索


Y!ログール