注意:
1.制作xml文件时候特别小心回车和Tab键,在解析程序,把他们也当做是有效字符,因此输出结果会跟预期不一样.
2.在从网上下载文件时读入文件流时候,需要添加StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
要不然下载文件会报错,下载文件失败。这个函数要求在API 9以上才可以使用,因此注意需要在AndroidManifest中配置
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="18" />
android:minSdkVersion要在9以上,如果为8,则系统将报错,无法编译。
3. 使笔记本调试Eclipse程序,有时候很多快捷键用不了是因为Eclipse很多快捷键跟笔记本的快捷键冲突,而系统优先系统的快捷键。加入一个外插键盘,eclipse快捷键就都能用了。
(1)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.xml" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.xml.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> </manifest>
(2)FileUtils.java
package com.example.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.os.Environment; public class FileUtils { private String SDPATH; public String getSDPATH() { return SDPATH; } public FileUtils() { SDPATH = Environment.getExternalStorageDirectory() + "/"; } public File createSDFile(String fileName) throws IOException { File file = new File(SDPATH + fileName); file.createNewFile(); return file; } public File createSDDir(String dirName) { File dir = new File(SDPATH + dirName); dir.mkdir(); return dir; } public boolean isFileExist(String strFileName) { File file = new File(SDPATH + strFileName); return file.exists(); } public File write2SDFromInput(String path, String fileName, InputStream input) { File file = null; OutputStream output = null; try { createSDDir(path); file = createSDFile(path + fileName); output = new FileOutputStream(file); byte buffer[] = new byte[4 * 1024]; while ((input.read(buffer)) != -1) { output.write(buffer); } output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { output.close(); } catch (Exception e) { e.printStackTrace(); } } return file; } }
(3)HttpDownloader.java
package com.example.utils; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.os.StrictMode; public class HttpDownloader { private URL url = null; public String download(String strUrl){ StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try{ StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); url = new URL(strUrl); HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); while ((line = buffer.readLine()) != null){ sb.append(line); } }catch (Exception e){ e.printStackTrace(); }finally{ try{ buffer.close(); }catch (Exception e){ e.printStackTrace(); } } return sb.toString(); } /** * * @param strUrl * @param strPath * @param strFileName * @return * * -1: error occurs when downloading; 0: downloaded successfully; 1: the downloading file already exists */ public int downFile(String strUrl, String strPath, String strFileName){ InputStream inputStream = null; try{ FileUtils fileUtils = new FileUtils(); if (fileUtils.isFileExist(strPath + strFileName)){ return 1; } else { inputStream = getInputStreamFromUrl(strUrl); File resultFile = fileUtils.write2SDFromInput(strPath, strFileName, inputStream); if (resultFile == null){ return -1; } } } catch (Exception e){ e.printStackTrace(); return -1; } finally{ try { inputStream.close(); } catch (Exception e){ e.printStackTrace(); } } return 0; } public InputStream getInputStreamFromUrl(String strUrl) throws MalformedURLException, IOException{ StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build()); url = new URL(strUrl); HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); InputStream inputStream = urlConn.getInputStream(); return inputStream; } }
(4)MainActivity.java
package com.example.xml; import java.io.StringReader; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import com.example.utils.HttpDownloader; public class MainActivity extends Activity { private Button parseXML = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); parseXML = (Button)findViewById(R.id.parseXML); parseXML.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub HttpDownloader hd = new HttpDownloader(); String strResult = hd.download("http://10.0.2.2:8080/examples/test.xml"); System.out.println(strResult); try { //使用Simple API for XML (SAX) 读取文件 //相对于DOM一次性按节点模式全读入内存,才能进行处理 //该类为边读边处理,读取操作可以随时中断,适合于超大型的xml文件 SAXParserFactory factory = SAXParserFactory.newInstance(); XMLReader reader = factory.newSAXParser().getXMLReader(); reader.setContentHandler(new MyContentHandler()); reader.parse(new InputSource(new StringReader(strResult))); } catch (Exception e) { e.printStackTrace(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
(5)MyContentHandler.java
package com.example.xml; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; //这里没有实现contentHandler接口是因为我们不需要重写所有接口函数 //我们采用继承模式,只需将需要重新的函数实现即可 public class MyContentHandler extends DefaultHandler{ String name1, address1, money1, sex1, status1; String tagName; /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int) */ @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub if (tagName.equals("name")) { name1 = new String(ch, start, length); } if (tagName.equals("sex")) { sex1 = new String(ch, start, length); } if (tagName.equals("status")) { status1 = new String(ch, start, length); } if (tagName.equals("address")) { address1 = new String(ch, start, length); } if (tagName.equals("money")) { money1 = new String(ch, start, length); } } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endDocument() */ @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub System.out.println("-----------end----------"); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub if (localName.equals("worker")) { this.printOut(); } } //之所以打印不来这些名称值,是因为在xml中存在"\t"这种符号 //需要对文件重新进行整理 public void printOut() { System.out.println("name: " + name1); System.out.println("sex: " + sex1); System.out.println("status: " + status1); System.out.println("address: " + address1); System.out.println("money: " + money1); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#startDocument() */ @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub System.out.println("------------begin-----------------"); } /* (non-Javadoc) * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub tagName = localName; if (localName.equals("worker")) { for (int i = 0; i < attributes.getLength(); i++) { System.out.println(attributes.getLocalName(i) + "=" + attributes.getValue(i)); } } } }