Android从xml获取属性值

时间:2017-10-01 18:24:12

标签: android xml

我正在尝试制作一个使用last.fm的网络API的应用,为类似艺术家发送查询并返回相似艺术家的所有名称。好像我设法连接并正确获取xml响应。但是,我无法提取name-attribute的值。我正在使用artistName = xmlData.getAttributeValue(null, "name");,但它给我的全部都是空的。

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;

@SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
    private final String INPUTERROR = "Invalid/missing artist name.";
    private NetworkCommunication nc;
    private ArrayList<String> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nc = new NetworkCommunication();
        nc.register(this);
        list = new ArrayList<>();

        ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
        ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        lv.setAdapter(adapter);
    }

    public void searchButton_Clicked(View v){
        EditText inputField = (EditText)findViewById(R.id.editText_artistName);
        String searchString = inputField.getText().toString();
        searchString = cleanSearchString(searchString);

        if(validateSearchString(searchString)){
            nc.setSearchString(searchString);
            nc.execute();
        }
        else{
            Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
        }
    }

    private String cleanSearchString(String oldSearchString){
        String newString = oldSearchString.trim();
        newString = newString.replace(" ", "");

        return newString;
    }

    private boolean validateSearchString(String searchString){
        boolean rValue = true;

        if(TextUtils.isEmpty(searchString)){
            rValue = false;
        }

        return rValue;
    }

    @Override
    public void update(String artistName) {
        list.add(artistName);
    }
}

这是我的网络通讯课程:

import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

@SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
    private final String MYAPIKEY = "--------------------------";
    private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
    private final String METHOD = "?method=artist.getsimilar";
    private ArrayList<Observer> observers;
    private int amountOfArtists = 0;
    private String foundArtistName;
    private String searchString;

    NetworkCommunication(){
        observers = new ArrayList<>();
    }

    void setSearchString(String newSearchString){
        searchString = newSearchString;
    }

    private XmlPullParser sendRequest(){
        try{
            URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
            XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
            receivedData.setInput(url.openStream(), null);
            return receivedData;
        }
        catch (IOException | XmlPullParserException e){
            Log.e("ERROR", e.getMessage(), e);
        }

        return null;
    }

    private int tryProcessData(XmlPullParser xmlData){
        int artistsFound = 0;
        String artistName;
        int eventType;

        try{
            while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {

                if (eventType == XmlPullParser.START_TAG) {
                    if(xmlData.getName().equals("name")){
                        artistName = xmlData.getAttributeValue(null, "name");
                        publishProgress(artistName);
                        artistsFound++;
                    }
                }
            }
        }
        catch (IOException | XmlPullParserException e){
            Log.e("ERROR", e.getMessage(), e);
        }

        if (artistsFound == 0) {
            publishProgress();
        }

        return artistsFound;
    }

    @Override
    protected Integer doInBackground(Object... params) {
        XmlPullParser data = sendRequest();
        if(data != null){
            return tryProcessData(data);
        }
        else{
            return null;
        }
    }

    @Override
    protected void onProgressUpdate(String... values){
        /*
        if (values.length == 0) {
            //No data found...
        }
        */
        if (values.length == 1) {
            setFoundArtistName(values[0]);
            notifyObserver();
        }

        super.onProgressUpdate(values);
    }

    private void setFoundArtistName(String newArtistName){
        foundArtistName = newArtistName;
    }

    @Override
    public void register(Observer newObserver) {
        observers.add(newObserver);
    }

    @Override
    public void unregister(Observer deleteObserver) {
        observers.remove(deleteObserver);
    }

    @Override
    public void notifyObserver() {
        for (Observer o : observers) {
            Log.i("my tag.... ", "name = " + foundArtistName);
            o.update(foundArtistName);
        }
    }
}

以下是Google Chrome中xml响应的屏幕截图:

XML-response as shown in Google Chrome

此时我唯一感兴趣的是Name-Element的值。

我正在记录foundArtistName的值(在方法notifyObserver中)它给了我很多&#34;我的标签.... name = null我的标签.... name = null我的标签.... name = null等。&#34;

编辑:我尝试使用getText()代替getAttributeValue(),但它也让我为空。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我正在使用:artistName = xmlData.getAttributeValue(null, "name");,当我真的应该使用时:artistName = xmlData.nextText();