下記のようなファイルをxpathで読もうとします。
id01 car1 id02 car2
読み込むソースは下記です。
import javax.xml.parsers.* import javax.xml.xpath.* import org.w3c.dom.* // documentの作成 def path = "C:\\englishpass\\car.txt" DocumentBuilderFactory f = DocumentBuilderFactory.newInstance() f.setNamespaceAware(true) DocumentBuilder b= f.newDocumentBuilder() Document doc = b.parse(path) // xpathの作成 XPathFactory xf = XPathFactory.newInstance() XPathxpath = xf.newXPath() XPathExpression exp = xpath.compile("/cars/car/name/text()") // 読み込み Object ret = exp.evaluate(doc, XPathConstants.NODESET) NodeList nodes = (NodeList) ret nodes.each{ println it.getNodeValue() }
パスがasciiのみの場合は正常に結果が取得されます。
car1 car2
DocumentBuilderのparseメソッドに渡すパスに日本語が含まれている場合、エラーが発生しました。
def path = "C:\\日本語のパス\\car.txt
xercesのパーサが日本語に対応していないのが原因らしいです。
なので、パス文字列でなく入力ストリームをparseメソッドに渡す方法に変更。
def path = "C:\\日本語のパス\\car.txt" // FileInputStreamのインスタンスを作成 def f = new FileInputStream(path) DocumentBuilderFactory f= DocumentBuilderFactory.newInstance() f.setNamespaceAware(true) DocumentBuilder b= f.newDocumentBuilder() // parseメソッドにFileInputStreamを渡す Document doc = b.parse(f)
これで日本語のパスを含むファイルを解析できました。
もしくはparse(new File(path))でもOKなようです。
中身が日本語の場合大丈夫なのかというと、UTF-8の場合はそのまま使えました。
Shift_JISの場合はXMLファイルの頭に
<?xml version="1.0" encoding="Shift_JIS" ?>
のような指定をしておけばプログラム的には何もしなくても読めました。
文字コードを明示的に指定する場合は、InputSourceを利用できます。
import org.xml.sax.InputSource def f = new FileInputStream(path) def s = new InputSource(f) s.setEncoding("Shift_JIS") // ... Document doc = b.parse(s)