解析 XML文件 到哈希MAP
解析XML 文件是 android开发中常遇到的需求,以下是一种实现方式。
如何解析呢? android 中通常用PullXmlParser。 public Map<String,String> parseWallpaperXml2Map( String filePath ) { File file = new File( filePath); InputStream inStream =null; try{ inStream = new FileInputStream( file ); }catch( FileNotFoundException e){ e.printStackTrace(); }catch( IOException e ){ e.printStackTrace(); } Map <String,String > redirectionMap = new HashMap<String,String > (); XmlPullParser parser = Xml.newPullParser(); Log.v( TAG,"Begin"); try{ parser.setInput( inStream,"UTF-8"); int eventType = parser.getEventType(); String resType = null; String resName = null; String resText = null; String drawableName = null; String attriName = null; String attriValue = null; List<String> valList = null; while( eventType != XmlPullParser.END_DOCUMENT ){ if( XmlPullParser.START_TAG == eventType ){ resType = parser.getName(); if( null != resType && resType.equalsIgnoreCase("drawable") ){ attriName = parser.getAttributeName(0); attriValue = parser.getAttributeValue(null,attriName); resName = parser.nextText(); if( null != resName && attriValue != null ){ redirectionMap.put(attriValue,resName); } } } eventType = parser.next(); } Log.v( TAG,"End"); }catch(XmlPullParserException e){ e.printStackTrace(); }catch( IOException e ){ e.printStackTrace(); } return redirectionMap; }
至此返回了一个MAP 。这个MAP 中的键值对和 XML 文件中的键值对是一一对应的。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |