【发布时间】:2017-05-31 10:09:06
【问题描述】:
我正在清理我的应用程序中的工作代码,我注意到我在代码中的多个位置重用了XPathFactory、XPath、XPathExpression 对象,并认为我会清理它设置并设置一个方法来做到这一点。我注意到的是,通常当您将 XML 文档发送到 XPathExpression.evalutate 方法时,您只需将其放在源参数中,就像这样。
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
Document builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new FileReader("/path/to/file.xml"));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile("path/to/node");
Object result = expression.evaluate(document, XPathConstants.NODE);
这很好,但是当我尝试将 XPath 部分包装到这样的单独方法中时:
private Object getObjectByExpression(String expr, InputSource source, QName objectType)
{
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expression = xpath.compile(expr);
Object result = expression.evaluate(document, objectType);
return result;
}
public void someCalledMethod()
{
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
Document builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new FileReader("/path/to/file.xml"));
Object result = getObjectByExpression("/path/to/node", document, XPathConstants.NODE);
}
Eclipse 告诉我必须将 document 转换为 InputSource 并将其标记为错误。我确实仔细检查了 XPathExpression.evaluate 中使用的 InputSource 和我的方法中的类类型是否相同。有没有人对这种不一致的来源有更深入的了解?
【问题讨论】:
标签: java xpath parameter-passing