解析 XML文件 到哈希MAP

前端之家收集整理的这篇文章主要介绍了解析 XML文件 到哈希MAP前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


解析XML 文件是 android开发中常遇到的需求,以下是一种实现方式。



xml 文件如下:
<?xml version="1.0" encoding="utf-8"?>
<items>
<drawable name="wallpaper_00">大海</drawable>
<drawable name="wallpaper_01">高山</drawable>
<drawable name="wallpaper_02">草原</drawable>
<drawable name="wallpaper_03">光线</drawable>
<drawable name="wallpaper_04">折影</drawable>
<drawable name="wallpaper_05">幽谷</drawable>
<drawable name="wallpaper_06">大桥</drawable>
<drawable name="wallpaper_07">城市</drawable>
<drawable name="wallpaper_08">五彩</drawable>
<drawable name="wallpaper_09">炫光</drawable>
<drawable name="wallpaper_10">视觉</drawable>
<drawable name="wallpaper_11">平凡之路</drawable>
<drawable name="wallpaper_12">碎花</drawable>
</items>


如何解析呢? 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 文件中的键值对是一一对应的。

原文链接:https://www.f2er.com/xml/296107.html

猜你在找的XML相关文章