Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a simple way in java to evaluate an xpath on a string and return a result string

Tags:

java

xml

xpath

A simple answer needed to a simple question.

For example:

String xml = "<car><manufacturer>toyota</manufacturer></car>";
String xpath = "/car/manufacturer";
assertEquals("toyota",evaluate(xml, xpath));

How can I write the evaluate method in simple and readable way that will work for any given well-formed xml and xpath.

Obviously there are loads of ways this can be achieved but the majority seem very verbose.

Any simple ways I'm missing/libraries that can achieve this?

For cases where multiple nodes are returned I just want the string representation of this.

like image 900
Pablojim Avatar asked Nov 16 '10 18:11

Pablojim


People also ask

What does XPath evaluate return?

expression - The XPath expression. source - The InputSource of the document to evaluate over. Returns: The String that is the result of evaluating the expression and converting the result to a String .

What is XPath parsing?

It defines a language to find information in an XML file. It is used to traverse elements and attributes of an XML document.


2 Answers

Here you go, the following can be done with Java SE:

import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

public class Demo {

    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))));
    }

}
like image 67
bdoughan Avatar answered Oct 16 '22 22:10

bdoughan


For this use case the XMLUnit library may be a perfect fit: http://xmlunit.sourceforge.net/userguide/html/index.html#Xpath%20Tests

It provides some additional assert methods.

For example:

assertXpathEvaluatesTo("toyota", "/car/manufacturer",
    "<car><manufacturer>toyota</manufacturer></car>");
like image 38
vanje Avatar answered Oct 16 '22 20:10

vanje