@634

634 - JAXP - DOM - ルート要素名の取得

Advertisement

Element

ルート要素名を取得するためにはgetDocumentElementメソッドを実行します。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();

            // タグ名の表示
            System.out.println(root.getTagName());
        }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>

結果
document

Advertisement

ショートカット

634
このカテゴリのトップページに戻る
634labs
   UIコレクションギャラリー

サイト検索

Google

Web サイト内

Y!ログール