Android XmlResourceParser解析Xm文件实例

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

1.timezones.xml:


    Douala
    Kampala
    Kano
    Khartoum
    Kinshasa
    Lagos
    Luanda
    Lusaka
    Maputo
    Monrovia


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日志:

Android XmlResourceParser解析Xm文件实例_第1张图片

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

 

 

你可能感兴趣的:(Android,xml解析)