使用Java中的属性解析XML?

时间:2011-10-10 21:16:45

标签: java xml xml-parsing

我有一个网址:http://ws.audioscrobbler.com/2.0/?method=chart.getlovedtracks&api_key=b25b959554ed76058ac220b7b2e0a026&page=3&limit=25,用于显示有关歌曲名称和艺术家信息的XML。它还显示3个链接到不同大小的图像,这些图像URL由

标识
<image size="small">
<image size="large">
<image size="extralarge">  

这是我目前正在使用的代码但是我不知道如何只获取中等大小的图像的网址???

private void parseXml(String urlPath) throws Exception {
    URL url = new URL(urlPath);
    URLConnection connection = url.openConnection();
    DocumentBuilder db = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();

    final Document document = db.parse(connection.getInputStream());
    XPath xPathEvaluator = XPATH_FACTORY.newXPath();
    XPathExpression nameExpr = xPathEvaluator.compile("lfm/tracks/track/name");
    NodeList trackNameNodes = (NodeList) nameExpr.evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < trackNameNodes.getLength(); i++) {
        Node trackNameNode = trackNameNodes.item(i);
        System.out.println(String.format("Track Name: %s" , trackNameNode.getTextContent()));

        XPathExpression artistImageExpr = xPathEvaluator.compile("following-sibling::/image");
        NodeList artistImageNodes = (NodeList) artistImageExpr.evaluate(trackNameNode, XPathConstants.NODESET);
        for (int j=0; j < artistImageNodes.getLength(); j++) {
            System.out.println(String.format(" -Image URL: %s", artistImageNodes.item(j).getTextContent()));
        }

        XPathExpression artistNameExpr = xPathEvaluator.compile("following-sibling::artist/name");
        NodeList artistNameNodes = (NodeList) artistNameExpr.evaluate(trackNameNode, XPathConstants.NODESET);
        for (int j=0; j < artistNameNodes.getLength(); j++) {
            System.out.println(String.format(" - Artist Name: %s", artistNameNodes.item(j).getTextContent()));
        }
    }
}

0 个答案:

没有答案