javax.xml.parsers.DocumentBuilderを利用して、XMLドキュメントを処理しようとした際、下記のコードの3行目でMalformedByteSequenceExceptionという例外が発生した。
1: DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); 2: DocumentBuilder builder = dbfactory.newDocumentBuilder(); 3: Document doc = builder.parse(new File(filename)); 4: Element root = doc.getDocumentElement();
実際には以下のようなエラーが出力されたのだが、その原因は読み込んでいるXMLドキュメントのXML宣言で、文字コードの指定が抜けていたためであった。
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.
XMLドキュメント内の日本語の文字コードがUTF-8の場合には、文字コードの指定が抜けていても問題が無いようなのだが、Shift_JISで書かれている場合には下記のような文字コードの指定が無いと、上記のようなエラーが出力されるもよう。
<?xml version="1.0" encoding="Shift_JIS"?>