1

我有以下来自 vimeo 的 xml 文件:http: //vimeo.com/api/v2/video/21331554.xml

我正在尝试使用以下代码提取缩略图媒体:

File fXmlFile = new File("http://vimeo.com/api/v2/video/" + linkId + ".xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
return ((Node) doc.getElementsByTagName("thumbnail_medium")).getNodeValue();

但我得到“未定义”作为回报

4

1 回答 1

1

您不能将NodeList 强制转换为Node所以这一行:

return ((Node) doc.getElementsByTagName("thumbnail_medium")).getNodeValue();

抛出一个 ClassCastException。因此,您需要获取 NodeList 中的唯一项目并使用以下行获取其文本值:

return doc.getElementsByTagName("thumbnail_medium").item(0).getTextContent();

我用这两种方法对此进行了测试:

@Test
public void domTestVimeo() throws ParserConfigurationException,
        SAXException, IOException {

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(new ClassPathResource("vimeo.xml")
            .getInputStream());
    doc.getDocumentElement().normalize();

    String val = ((Node) doc.getElementsByTagName("thumbnail_medium"))
            .getNodeValue();

    System.out.println(val);

}

@Test
public void yourTest() throws ParserConfigurationException, SAXException,
        IOException {
    // File fXmlFile = new File("http://vimeo.com/api/v2/video/" + 21331554
    // + ".xml");

    InputStream is = new ClassPathResource("vimeo.xml").getInputStream();

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(is);
    doc.getDocumentElement().normalize();
    String val = doc.getElementsByTagName("thumbnail_medium").item(0)
            .getTextContent();

    System.out.println(val);

}

第一个抛出 ClassCastException ,第二个打印http://b.vimeocdn.com/ts/137/151/137151977_200.jpg我认为这是您正在寻找的值。

另外,您是如何从传递 URL 的 File 对象中读取的?

于 2012-11-15T00:13:10.963 回答