我试图只获取属性的一部分(也可以是元素的一部分),但到目前为止还没有得到任何结果。我得到的例外是“无效的XPath表达式: //@att/tokenize(.,‘').预期的节点类型”。我使用的是dom4j 1.6.1。
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.XPath;
import org.dom4j.xpath.DefaultXPath;
public class TestXPathString {
/**
* @param args
* @throws DocumentException
*/
public static void main(String[] args) throws DocumentException {
Document doc = DocumentHelper
.parseText("<x><y att='I just need the first word' /></x>");
XPath xpath = new DefaultXPath("//@att/tokenize(., ' ')[.][position() = 1]");
Object result = xpath.evaluate(doc);
System.out.printf("Type: %s, Value: %s\n", result.getClass()
.getSimpleName(), result);
}
}它不适用于
doc.selectObject("//@att/substring-before(., ' ')");都不是。
有什么想法吗?
发布于 2014-02-25 09:54:49
在axis步骤中应用函数是Java2.0的一个特性;XPath (和dom4j)只支持XPath 1.0。你不能这么做。
如果您只期望得到一个结果,请使用substring-before(//@att, ' ')。否则,将整个属性值传递给Java,并在XPath之外执行字符串操作。
您可以考虑使用Java插入功能更强大的XPath/XQuery引擎,如Saxon、BaseX或其他原生XML数据库。
发布于 2014-02-25 08:59:35
使用
//*/substring-before(@att, ' ')发布于 2014-02-25 14:40:01
您可以使用撒克逊XPath 2.0引擎来查询DOM4J。然后你的表情就能用了。
https://stackoverflow.com/questions/22008936
复制相似问题