我尝试只获取属性的一部分(也可能是元素的一部分),但到目前为止还没有运气。我得到的异常是“无效的 XPath 表达式://@att/tokenize(., ' ')[.][position() = 1] 预期的节点类型”。我正在使用 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(., ' ')");
都可以。
有什么想法吗?
最佳答案
在轴步骤中应用函数是 XPath 2.0 的一项功能; Java(和 dom4j)仅支持 XPath 1.0。你不能这样做。
如果您只期望得到一个结果,请使用substring-before(//@att, ' ')
。否则,将整个属性值传递给 Java 并在 XPath 之外进行字符串操作。
您可能会考虑插入更强大的 XPath/XQuery 引擎,例如 Saxon、BaseX 或其他具有可用 Java API 的 native XML 数据库。
关于java - dom4j XPath 不是节点类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22008936/