一个简单问题所需要的简单答案。
例如:
String xml = "<car><manufacturer>toyota</manufacturer></car>";
String xpath = "/car/manufacturer";
assertEquals("toyota",evaluate(xml, xpath));
如何以简单且可读的方式编写适用于任何给定的格式良好的xml和xpath的evaluate方法。
显然,有很多方法可以实现这一点,但大多数方法似乎非常冗长。
有什么简单的方法可以实现这一点吗?
对于返回多个节点的情况,我只需要它的字符串表示。
发布于 2010-11-17 02:33:47
在这里,可以使用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))));
}
}
发布于 2010-11-17 05:29:56
对于这个用例,XMLUnit库可能是一个完美的选择:http://xmlunit.sourceforge.net/userguide/html/index.html#Xpath%20Tests
它提供了一些附加的断言方法。
例如:
assertXpathEvaluatesTo("toyota", "/car/manufacturer",
"<car><manufacturer>toyota</manufacturer></car>");
发布于 2014-09-03 09:39:11
使用https://github.com/guppy4j/libraries/tree/master/messaging-impl中的Xml类:
Xml xml = new Xml("<car><manufacturer>toyota</manufacturer></car>");
assertEquals("toyota", xml.get("/car/manufacturer"));
https://stackoverflow.com/questions/4197507
复制相似问题