解析XML XPath - for循环访问所有元素而不是仅访问特定标记的元素

时间:2015-12-07 10:57:58

标签: java xml parsing xpath xml-parsing

我正在尝试解析一个xml文件,其中包含有关itunes上播放列表的信息。我已成功设法解析有关播放列表名称和ID的信息,但我无法获取播放列表中的歌曲,因为for循环遍历每个播放列表中的所有歌曲然后全部显示。我希望每个播放列表都有所不同。

        NodeList tList = (NodeList) x.evaluate("/plist/dict/array/dict/array/dict", root, XPathConstants.NODESET);
        for (int j = 0; j < tList.getLength(); ++j) {
            Element track = (Element) tList.item(j);

            Double trackId = (Double) x.evaluate("key[.='Track ID']/following-sibling::integer[1]", track,
                    XPathConstants.NUMBER);
            tracks.add(trackId);
            p.setTracks(tracks);

        }
        Playlist play = new Playlist(name, persistentID, playlistId, tracks);
        System.out.println(p.toString());
    }

输出:

Playlist [name=Music, persistentId=29E12A03204E072C, playlistId=2687.0, tracks=[1234.0, 1282.0, 1694.0, 1558.0, 1802.0, 1280.0, 1278.0, 1656.0, 1298.0, 1334.0, 1294.0, 398.0, 400.0, 402.0, 404.0, 406.0, 408.0, 412.0, 414.0, 416.0, 418.0, 422.0, 424.0, 426.0, 430.0...]
Playlist [name=Purchased, persistentId=29E12A03204E072C, playlistId=2687.0, tracks=[1234.0, 1282.0, 1694.0, 1558.0, 1802.0, 1280.0, 1278.0, 1656.0, 1298.0, 1334.0, 1294.0, 398.0, 400.0, 402.0, 404.0, 406.0, 408.0, 412.0, 414.0, 416.0, 418.0, 422.0, 424.0, 426.0, 430.0....]

我希望每首歌曲的曲目ID与其特定的播放列表相关,但我不知道如何实现这一点。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

ArrayList<Double> tracks = new ArrayList<Double>();移动到第一个循环中并使用相对的XPath表达式:

    NodeList tList = (NodeList) x.evaluate("array/dict", dict, XPathConstants.NODESET);
    ArrayList<Double> tracks = new ArrayList<Double>();
    for (int j = 0; j < tList.getLength(); ++j) {
        Element track = (Element) tList.item(j);