2015年7月14日火曜日

JavaでXMLを読み込む(DOM版)

PowerShellでXMLを読み込む方法を書いたので、
今度はJavaで読み込む方法も書いてみた。
DOM使って読み込む。

まあ......手順としては理解しやすいけどめんどいね。
以下のファイルを読み込んでみた。


 

    ChildA
    ChildB
    ChildC


コードの全体の流れとしてはこんな感じ。

  1. Fileをインスタンス化
  2. DocumentBuilderFactoryをインスタンス化
  3. DocumentBuilderをインスタンス化
  4. DocumentBuilderを使って1をparseしてDocumentをインスタンス化
  5. 4.からElementにxml文書のルートノードを格納
  6. ElementからNodeListを取得
6はここでは、getElementsByTagIdメソッドを使っている。
getChildNodeでも同じ結果が得られると思って使ってみると、なんか
NodeListのgetLengthメソッドの結果が違う......
これは要調査。

package variouslibraries.javalearning.xml;

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 XMLReader {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        File file;
        file = new File("./SampleXML.xml");
        
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(file);
        
        Element root = document.getDocumentElement();
        System.out.println("Root要素のタグ名:"+root.getNodeName());
        
        System.out.println("子要素を取得して値を表示。");
        NodeList children = root.getElementsByTagName("Child");
        for(int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            System.out.println(node.getTextContent());
        }        
    }
}


実行結果

Root要素のタグ名:Parent
子要素を取得して値を表示。
ChildA
ChildB
ChildC

0 件のコメント:

コメントを投稿