有一些非常好的開源XML解析工具可以讓這個更容易。例如,用Simple XML解決這個問題,我會做這樣的:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.squareup.okhttp.OkHttpClient;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
URL website = new URL("http://vestsoft.somee.com/api/scores");
OkHttpClient client = new OkHttpClient();
HttpURLConnection conn = client.open(website);
conn.addRequestProperty("Accept", "application/xml");
InputStream stream = conn.getInputStream();
Serializer serializer = new Persister();
ArrayOfScore scoreArray = serializer.read(ArrayOfScore.class, stream);
// do something with the ArrayScore object here
} catch (Exception err) {
Log.i(TAG, err.toString());
}
}
};
new Thread(r).start();
}
});
}
}
此引用其他兩個類中,XML註解的Java類。它們是:
import java.util.List;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;
@Root
public class ArrayOfScore {
@ElementList(inline=true,required=false)
private List<Score> scores;
public List<Score> getScores() {
return scores;
}
}
和:
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name="Score")
public class Score {
@Element(name="Id",required=false)
Integer Id;
@Element(name="Name",required=false)
String Name;
@Element(name="Points",required=false)
String Points;
@Element(name="dateTime",required=false)
String dateTime;
}
有了這個簡單的模型,你可以分析幾乎你遇到的任何XML,並得到解析成第一類對象自動。有類似的JSON類,如Gson
你能粘貼整個堆棧跟蹤嗎?我猜XML格式不正確。 – CodeChimp
我該如何得到它? 在「Java堆棧跟蹤控制檯」中沒有任何內容。 – FlipEX
我認爲你需要先將數據下載/讀取到緩衝區,然後才能解析它。 –