XML文件操作(二)
2.DOM解析
1 //获得工厂 2 DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); 3 //获得解析对象 4 DocumentBuilder builder=dbf.nwDocumentBuilder(); 5 //读取资源文件 6 InputStream is=getResources().openRawResource(R.raw.books); 7 Document doc=builder.parse(is); 8 //获得books的所有子节点 9 NodeList list=doc.getElementsByTagName("book"); 10 for(int i=0;i<list.getLength();i++){ 11 Element element=(Element) list.item(i); 12 //获得name子节点的值 13 String valueString=element.getElementsByTagName("name") 14 .item(0).getFirstChild().getNodeValue(); 15 Toast.makeText(this, valueString, 3000).show(); 16 }
3.PULL解析
1 // 创建解析器工厂 2 XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); 3 // 创建解析器对象 4 XmlPullParser parser = factory.newPullParser(); 5 // 读取资源文件 6 InputStream is = getResources().openRawResource(R.raw.books); 7 // 设置输入流对象和编码格式 8 parser.setInput(is, "UTf-8"); 9 // 获取事件类型 10 int type = parser.getEventType(); 11 while (type != XmlPullParser.END_DOCUMENT) { 12 // 获取标签名称 13 String name = parser.getName(); 14 15 if ("name".equals(name)&&type==XmlPullParser.START_TAG) { 16 type=parser.next(); 17 Toast.makeText(this, parser.getText(), 300).show(); 18 } 19 type=parser.next(); 20 }
文件操作
//保存文件的操作
1 try { 2 OutputStream os=openFileOutput("a.txt",Activity.MODE_PRIVATE ); 3 PrintWriter pw=new PrintWriter(os); 4 pw.println("abcdefg"); 5 pw.println("hijkmnl"); 6 pw.close(); 7 } catch (FileNotFoundException e) { 8 // TODO Auto-generated catch block 9 e.printStackTrace(); 10 }
//读取文件操作
1 try { 2 FileInputStream fis=openFileInput("a.txt"); 3 BufferedReader bra=new BufferedReader( 4 new InputStreamReader(fis)); 5 String str=null; 6 while ((str=bra.readLine())!=null) { 7 Log.i("str", str); 8 } 9 } catch (FileNotFoundException e) { 10 // TODO Auto-generated catch block 11 e.printStackTrace(); 12 } catch (IOException e) { 13 // TODO Auto-generated catch block 14 e.printStackTrace(); 15 }