What's a simple way in java to evaluate an xpa

2020-03-08 08:16发布

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.

标签: java xml xpath
3条回答
放荡不羁爱自由
2楼-- · 2020-03-08 08:47

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

}
查看更多
姐就是有狂的资本
3楼-- · 2020-03-08 08:54

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>");
查看更多
看我几分像从前
4楼-- · 2020-03-08 09:01

Using the Xml class from https://github.com/guppy4j/libraries/tree/master/messaging-impl :

Xml xml = new Xml("<car><manufacturer>toyota</manufacturer></car>");
assertEquals("toyota", xml.get("/car/manufacturer"));
查看更多
登录 后发表回答