读取XML文件

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

/**
 * This example shows how to read xml file from res/xml folder
 *
 * @author FaYnaSoft Labs
 *
 */
public class Main extends Activity {
	private static String APP_TAG = "tag";
	private TextView textView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		textView = (TextView) findViewById(R.id.textField);
		findViewById(R.id.readBtn).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				XmlPullParser parser = getResources().getXml(R.xml.cars);
				StringBuilder stringBuilder = new StringBuilder();
				try {
					while (parser.next() != XmlPullParser.END_DOCUMENT) {
						String name = parser.getName();
						String position = null;
						String brand = null;
						if((name != null) && name.equals("car")) {
							int size = parser.getAttributeCount();
							for(int i = 0; i < size; i++) {
								String attrName = parser.getAttributeName(i);
								String attrValue = parser.getAttributeValue(i);
								if((attrName != null) && attrName.equals("position")) {
									position = attrValue;
								} else if ((attrName != null) && attrName.equals("brand")) {
									brand = attrValue;
								}
							}
							if((position != null) && (brand != null)) {
								stringBuilder.append(position + ", " + brand + "\n");
							}
						}
						textView.setText(stringBuilder.toString());
					}
				}catch(Exception e) {
					Log.e(APP_TAG, e.getMessage());
				}
			}
		});
	}
}

 

你可能感兴趣的:(android,xml,OS)