top / index / prev / next / target / source

2017-01-20 diary: [Java] XPath のシンプルサンプル

いがぴょんの日記 日記形式でつづる いがぴょんコラム ウェブページです。

[Java] XPath のシンプルサンプル

JavaXPath を扱う書き方をよく忘れるのでこれをメモします。

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class App {
  public static void main(final String[] args) throws IOException {
    final String html = "<html><head><title>こんにちは世界</title></head><body></body></html>";
    final Document document = string2Document(html);

    try {
      final XPath xpath = XPathFactory.newInstance().newXPath();
      final String title = (String) xpath.evaluate("/html/head/title/text()", document, XPathConstants.STRING);

      System.err.println(title);
    } catch (XPathExpressionException e) {
      throw new IOException(e);
    }
  }

  public static Document string2Document(final String xml) throws IOException {
    try {
      final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
      return documentBuilder.parse(new InputSource(new StringReader(xml)));
    } catch (ParserConfigurationException e) {
      throw new IOException(e);
    } catch (SAXException e) {
      throw new IOException(e);
    }
  }
}

登場キーワード


この日記について