Java HTML / XML How to - Evaluate an xpath on a string and return a result string








Question

We would like to know how to evaluate an xpath on a string and return a result string.

Answer

import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
/*from w w  w.j a v a  2  s.  c  o  m*/
public class Main {

    public static void main(String[] args) throws Exception {
        String xml = "<car><manufacturer>toyota</manufacturer></car>";
        String xpath = "/car/manufacturer";
        XPath xPath = XPathFactory.newInstance().newXPath();
        assertEquals("toyota",xPath.evaluate(xpath, new InputSource(new StringReader(xml))));
    }

}