在java中评估字符串上的xpath并返回结果字符串的简单方法是什么 [英] What's a simple way in java to evaluate an xpath on a string and return a result string
本文介绍了在java中评估字符串上的xpath并返回结果字符串的简单方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个简单问题需要一个简单的答案。
A simple answer needed to a simple question.
例如:
String xml = "<car><manufacturer>toyota</manufacturer></car>";
String xpath = "/car/manufacturer";
assertEquals("toyota",evaluate(xml, xpath));
如何以简单易读的方式编写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 SE完成以下操作:
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))));
}
}
这篇关于在java中评估字符串上的xpath并返回结果字符串的简单方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文