为什么在传递给XPathExpression.evalutate方法时不需要转换Document对象?

时间:2017-05-31 10:09:06

标签: java xpath parameter-passing

我正在做一些工作清理我的应用程序中的工作代码,我注意到我在多个地方重用XPathFactoryXPathXPathExpression个对象我的代码,并想通知我会清理它并设置一个方法来执行此操作。我注意到的是,通常当您将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和我的方法中的InputSource是否是相同的类类型。有没有人对这种不一致的地方有更深入的了解?

1 个答案:

答案 0 :(得分:1)

实际上,Document使用XPathExpression.evaluate(Object, QName)方法。

Document是一个界面,因此它无法通过课程InputSource进行抄袭。这不可能。这就是您需要更新方法的原因:

private Object getObjectByExpression(String expr, Object source, QName objectType)

或者,如果您真的想将此限制为Document

private Object getObjectByExpression(String expr, Document source, QName objectType)