您不能将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 对象中读取的?