Android XmlResourceParser解析Xm文件实例

本篇将通过一个实例介绍一下下XmlResourceParser解析xml文件的具体方法,首先给出xml文件结构:

1.timezones.xml:

<timezones>
    <timezone id="GMT+01:00" weatherID="1478198">Douala</timezone>
    <timezone id="GMT+03:00" weatherID="20070421">Kampala</timezone>
    <timezone id="GMT+01:00" weatherID="1396803">Kano</timezone>
    <timezone id="GMT+03:00" weatherID="1433559">Khartoum</timezone>
    <timezone id="GMT+01:00" weatherID="1290062">Kinshasa</timezone>
    <timezone id="GMT+01:00" weatherID="2346342">Lagos</timezone>
    <timezone id="GMT+01:00" weatherID="1261906">Luanda</timezone>
    <timezone id="GMT+02:00" weatherID="1569006">Lusaka</timezone>
    <timezone id="GMT+02:00" weatherID="1550363">Maputo</timezone>
    <timezone id="GMT+00:00" weatherID="2453077">Monrovia</timezone>
</timezones>


2.解析xml文件关键代码:

 /**
	 * get info from a xml file.
	 */
	public void getXMLContent() {
		XmlResourceParser xrp = null;
		try {
			xrp = getResources().getXml(R.xml.timezones);
			while (xrp.next() != XmlResourceParser.START_TAG) {
				continue;
			}
			xrp.next();
			int readCount = 0;
			while (xrp.getEventType() != XmlResourceParser.END_TAG) {
				while (xrp.getEventType() != XmlResourceParser.START_TAG) {
					if (xrp.getEventType() == XmlResourceParser.END_DOCUMENT) {
						return;
					}
					xrp.next();
				}
				if (xrp.getName().equals("timezone")) {
					String id = xrp.getAttributeValue(TIMEZONE_ID);
					String weatherID = xrp.getAttributeValue(WEATHER_ID);
					String displayName = xrp.nextText();
					
					mCalendar.setTimeZone(TimeZone.getTimeZone(id));
					if (readCount < 50) {
						
					    android.util.Log.e(TAG,"id:"+id+"--DigitTimeZone:"+getDigitTimeZone(id));
					    android.util.Log.e(TAG,"weatherID:"+weatherID);
					    android.util.Log.e(TAG,"displayName:"+displayName+"--time:"+DateFormat.format(mIs24HoursMode ? "k:mm" : "h:mmaa", mCalendar));
					    
						readCount++;
					}
				}
				while (xrp.getEventType() != XmlResourceParser.END_TAG) {
					xrp.next();
				}
				xrp.next();
			}
			mNumberInXml = readCount;
			android.util.Log.v(TAG,"id:"+mNumberInXml);
			xrp.close();
		} catch (XmlPullParserException xppe) {
			Log.e(TAG, "Ill-formatted timezones.xml file");
		} catch (java.io.IOException ioe) {
			Log.w(TAG, "Unable to read timezones.xml file");
		} finally {
			if (null != xrp) {
				xrp.close();
			}
		}
	}


PS:

(1).根据解析出来的时区ID,可以得到对应的数字时区:

	public int getDigitTimeZone(String id) {
		TimeZone mTimeZone = TimeZone.getTimeZone(id);
		int digitTimeZone = mTimeZone.getRawOffset() / 60 / 60 / 1000;
		return digitTimeZone;
	}

(2).同时你也可以设置24小时制啥的,代码:

	//24小时制
	public void set24HoursMode(Context c) {
        mIs24HoursMode = android.text.format.DateFormat.is24HourFormat(c);;
    }

 

运行程序,log日志:



完整代码下载地址:http://download.csdn.net/detail/dadaxiaoxiaode/5834609

 

 

posted @ 2013-07-29 17:51  行走的思想  阅读(22)  评论(0编辑  收藏  举报  来源