Страница 1 из 1

Парсинг Last.FM

Добавлено: 09 янв 2015, 17:05
razmus
Здравствуйте!
Проблема с распарсиванием, беру данные по группе http://ws.audioscrobbler.com/2.0/?metho ... 640b250c17
И пытаюсь вытянуть фотографии с тегом <image size="large">, не могу понять почему не работает. Подскажите пожалуйста!

З.Ы.
Получить все элементы списка я могу но их может быть разное количество, а мне нужен именно с атрибутом large.

Код активити

Код: Выделить всё

public class LastFMParser extends ListActivity {

	static final String URL = "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist=Metallica&api_key=129b5bafd64fac60d0c096640b250c17";

	static final String KEY_ITEM = "artist";
	static final String KEY_NAME = "image";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

		XMLParser parser = new XMLParser();
		String xml = parser.getXmlFromUrl(URL);
		Document doc = parser.getDomElement(xml); 

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		for (int i = 0; i < nl.getLength(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
			menuItems.add(map);
		}

		ListAdapter adapter = new SimpleAdapter(this, menuItems,
				R.layout.list_item,
				new String[] { KEY_NAME, "", "" }, new int[] {
						R.id.name, R.id.desciption, R.id.cost });

		setListAdapter(adapter);
	}
	
}
Код парсера

Код: Выделить всё

public class XMLParser {

	public XMLParser() {

	}
	public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return xml;
	}
	
	public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}

	        return doc;
	}
	
	 public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }
	 
    public String getValue(Element item, String str) {
        
        NodeList n = item.getElementsByTagName(str);
        int find = 0;
        String Url = "";
        NodeList nList = item.getChildNodes();
        for (int i = 0; i < nList.getLength(); i++) {
            
            Node el = nList.item(i);
            if (el.getNodeName() != null && el.getNodeName().equalsIgnoreCase("image")) {
                try {
                    if (el.getAttributes().getNamedItem("size").getNodeValue().equalsIgnoreCase("large")) {
                        find = i;
                        Node child;
                        for (child = el.getFirstChild(); child != null; child = child.getNextSibling()) {
                            if (child.getNodeType() == Node.TEXT_NODE) {
                                Url =  child.getNodeValue();
                            }
                        }
                        
                    }
                } finally {
                    
                }
            }
            
        }
        return Url;
    }
}

Re: Парсинг Last.FM

Добавлено: 09 янв 2015, 18:18
razmus
Вопрос решил, поправил код парсера, может кому пригодится.