开发者

Parsing XML with attributes in Java?

I have a url: http://ws.audioscrobbler.com/2.0/?method=chart.getlovedtracks&api_key=b25b959554ed76058ac220b7b2e0a026&page=3&limit=25 that display XML with information on A song name and artist. It also display 3 links to different sized images, these image urls are identified by

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

Here is the code I am using at the moment however I do not know how to get the url for the medium sized image only ???

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 < artistNam开发者_StackOverflow社区eNodes.getLength(); j++) {
            System.out.println(String.format(" - Artist Name: %s", artistNameNodes.item(j).getTextContent()));
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜