我正在尝试检索搜索的第一个结果。搜索返回一个 xml 文件,我正在使用 sax 解析器处理该 xml。事实上,我想解析 xml 文件,并在处理完该搜索的第一个结果后停止。
即:我想解析这个文件: http://musicbrainz.org/ws/2/release?query=barcode: 606949062927并检索第一个结果(来自 Eminem 的专辑)。但是当我使用我的代码时,我存储了我不想要的最后一个结果(Daniel Swain 的专辑)。因此,如果我可以在第一个结果之后停止解析,这会好很多(耗时更少)。
我认为这可以通过设置一个 booleanfirstResult
来实现,并在我完成处理第一个结果时将其设置为 true,但我发现它真的很脏。你认为还有另一种方法吗?
这是我的代码的一部分:
public DataMusic parseBarcode(InputStream is) {
final DataMusic resultAlbum = new DataMusic();
RootElement root = new RootElement(ATOM_NAMESPACE,"metadata");
Element releaseList=root.getChild(ATOM_NAMESPACE,"release-list");
Element release = releaseList.getChild(ATOM_NAMESPACE,"release");
Element title = release.getChild(ATOM_NAMESPACE,"title");
Element artistCredit = release.getChild(ATOM_NAMESPACE,"artist-credit");
Element nameCredit = artistCredit.getChild(ATOM_NAMESPACE,"name-credit");
Element artist = nameCredit.getChild(ATOM_NAMESPACE,"artist");
Element artistName = artist.getChild(ATOM_NAMESPACE, "name");
releaseList.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attributes) {
if(attributes.getValue("count").equals(null) || attributes.getValue("count").equals("") || attributes.getValue("count").equals("0")) {
resultAlbum.setMBId(null);
resultAlbum.setAlbumName(null);
resultAlbum.setArtistName(null);
Log.w(TAG_MB, "Album was not found on MB. count=" + attributes.getValue("count") +".");
}
}
});
release.setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attributes) {
resultAlbum.setMBId(attributes.getValue("id"));
Log.v(TAG_MB, "Album found with id=" + attributes.getValue("id"));
}
});
title.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
Log.v(TAG_MB, "Album name set to " + body);
resultAlbum.setAlbumName(body);
}
});
artistName.setEndTextElementListener(new EndTextElementListener() {
@Override
public void end(String body) {
Log.v(TAG_MB, "Album artist name set to " + body);
resultAlbum.setArtistName(body);
}
});
try {
Log.v(TAG_MB, "Starting parsing data...");
Xml.parse(is, Xml.Encoding.UTF_8, root.getContentHandler());
Log.v(TAG_MB, "Finished parsing. Returning album with MBID=" + resultAlbum.getMBId() + " and name=" + resultAlbum.getAlbumName()) ;
return resultAlbum;
} catch (SAXException e) {
Log.e(TAG_MB + "_SAXException", "SAXException with MusicBrainz");
Log.e(LOGCAT_TAG + "_SAXException",e.getMessage());
} catch (IOException e) {
Log.w(TAG_MB+ "_IOException", "The HTTP Request wasn't good. Either 403 error, or the album wasn't found on LASTFM");
Log.w(LOGCAT_TAG+ "_IOException", "" + e.getMessage(), e);
}
return null;
}