是什么让我达到这一点:
我编写了一个XML Web服务,它提供来自存储在数据库中的CRM的数据。 XML Web服务的目的是让我能够以一种易于其他应用程序连接和读取的格式向外界提供一组有限的数据。 (或者我想)。
我的具体问题:
我需要在Android中编写一个可以从此Web服务解析XML并在本机应用程序中将其呈现给我的用户的应用程序。 连接到网站并将其拉下来并将其解析为对象的推荐方法是什么?
注意:
我无法向您展示XML的示例,因为测试服务器当前不面向Internet(很快就会)。我也不担心GUI开发。我将数据发送到手机后,我将解决这个问题。)。
答案 0 :(得分:2)
以下是我们的某个Android应用中的一些SAX代码。
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
//. . .
public class MyXmlHandler extends DefaultHandler
{
@Override
public void startDocument()
{
Log.i(TAG,"Starting to parse document.");
}
@Override
public void endDocument()
{
Log.i(TAG,"End of document.");
}
@Override
public void startElement(String uri,String localName,String qName,Attributes attributes)
{
if(localName.equals("myxmltag"))
{
//do something with myxmltag and attributes.
}
}
}
public void parseDocument()
{
try {
URL myxmlUri = new URL("file:///sdcard/appfolder/myxmldoc.xml");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
MyXmlHandler myxmlhandler = new MyXmlHandler();
xr.setContentHandler(myxmlhandler);
InputSource inputs = new InputSource(myxmlUri.openStream());
xr.parse(inputs);
// . . .
它的下载代码
private void downloadFile(String url, String destination) throws ParserConfigurationException, FileNotFoundException, SAXException, UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException {
if(isNetworkAvailable(this)){
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
get.setHeader("user_id", user_id);
reqEntity.addPart("user_id", new StringBody(user_id));
HttpResponse response = client.execute(get);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String serverResponse = EntityUtils.toString(resEntity);
BufferedWriter out = new BufferedWriter(new FileWriter(destination));
out.write(serverResponse);
out.close();
}
}
}
isNetworkAvailable
public static boolean isNetworkAvailable(Context context)
{
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
Log.w("tag", "Connectivity Manager failed to retrieve.");
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
您可能想要编辑downloadFile,以便在isNetworkAvailable返回false时会产生一些后果。
编辑:我删除了一些可能妨碍您的代码。我给了所有通用名称,以“我的”开头,而不是我的代码。