以下是我們的某個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。
編輯:我刪除了一些代碼,可能已經在你的方式。我給了一切以「my」開頭的通用名稱,而不是我的代碼中的內容。
用HTTP下載文件,然後用SAX解析器解析。 – Blundell 2011-04-26 14:17:59
謝謝。我現在正在閱讀SAX Parser! – 2011-04-26 14:26:23