[A-00177]JavaでXMLを読み込む

仕事都合でJavaでXMLを使用することになったので記載しておきます。

今回使用するAPIはDocumentBuilderです。

XMLファイルは用意せず、文字列からXMLを作成してそれを読み込ませます。

まずは正しくパースされる場合の例です。

package example;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws Exception {

        StringBuilder sb =new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
        sb.append("<ProgramingList>");
        sb.append("<Language id=\"001\" name=\"Java\">Javaは標準的なプログラミング言語です</Language>");
        sb.append("<Language id=\"002\" name=\"Python\">Pythonは標準的なプログラミング言語です</Language>");
        sb.append("</ProgramingList>");

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(sb.toString()));
        Document doc = builder.parse(is);
        Element elm = doc.getDocumentElement();
        NodeList list = elm.getElementsByTagName("Language");

        for (int i=0; i<list.getLength(); i++) {
            Element e = (Element)list.item(i);
            System.out.println(e.getAttribute("id"));
            System.out.println(e.getAttribute("name"));
        }
    }
}

実行すると下記のログが出力されます。

MacBook-Pro parse-xml % 
001
Java
002
Python

次に解析に失敗する例です。適当な文字列(XMLではない)を入力するとエラーを吐いてくれます。

package example;

import java.io.FileInputStream;
import java.io.StringReader;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * Hello world!
 *
 */
public class AppFail {
    public static void main( String[] args ) throws Exception {

        StringBuilder sb =new StringBuilder();
        sb.append("{\"Language\": \"Java\"}"); 

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(sb.toString()));
        Document doc = builder.parse(is);
        Element elm = doc.getDocumentElement();
        NodeList list = elm.getElementsByTagName("Language");

        for (int i=0; i<list.getLength(); i++) {
            Element e = (Element)list.item(i);
            System.out.println(e.getAttribute("id"));
            System.out.println(e.getAttribute("name"));
        }
    }
}

実行結果は下記のようになります。

MacBook-Pro parse-xml % 
[Fatal Error] :1:1: プロローグにはコンテンツを指定できません。
Exception in thread "main" org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; プロローグにはコンテンツを指定できません。
        at java.xml/com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:262)
        at java.xml/com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:342)
        at example.AppFail.main(AppFail.java:29)

・Appendix

参考文献はこちら

https://stackoverflow.com/questions/562160/in-java-how-do-i-parse-xml-as-a-string-instead-of-a-file

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*