我正在尝试使用YOURLS创建自定义URL缩短器。当我在YOURLS中使用内置API时,chrome中将其作为XML文档出现:

<result>
<url>
<keyword>2</keyword>
<url>http://www.bing.com</url>
<title>http://www.bing.com</title>
<date>2013-06-08 19:24:28</date>
<ip>127.0.0.1</ip>
</url>
<status>success</status>
<message>http://www.bing.com added to database</message>
<title>http://www.bing.com</title>
<shorturl>http://127.0.0.1/2</shorturl>
<statusCode>200</statusCode>
</result>


我只想要“ shorturl”中的内容

但是,我在日食中遇到错误

    URL url=null;
    try {
        url = new URL("http://localhost/yourls/yourls-api.php?username=username&password=password&action=shorturl&url="+"http://google.ca");
        BufferedReader reader = new BufferedReader(new InputStreamReader(url.openConnection().getInputStream()));
        String s = null;

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = (Document) db.parse((url).openStream());

        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression expr = (XPathExpression) xpath.compile("shorturl");
        Object exprResult = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodeList = (NodeList) exprResult;

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }




Object exprResult = expr.evaluate(doc, XPathConstants.NODESET);


该错误表明“类型为XPathExpressions的方法validate(Node,short,object)不适用于参数(Document,QName)”

有人知道如何解决此问题吗?

最佳答案

我的猜测是,您有一个名为XPathExpression的类的导入,但不是标准的javax.xml.xpath.XPathExpression。这也将解释为什么在代码中进行强制类型转换:

XPathExpression expr = (XPathExpression) xpath.compile("shorturl");


如果导入的类是javax.xml.xpath.XPathExpression,则不需要。编译器可能对简单的分配不满意,IDE提议通过添加强制转换来“修复”它。但是问题是您导入了错误的类。

10-08 17:51