android 怎么读取一个xml

2025-02-01 04:08:29
推荐回答(1个)
回答1:

  关于具体使用方法,举例如下:
  1、updatelog.xml文件位于res/xml/文件夹下:
  
  
    version="1.0"
  versioncode="1.1">
  1、这个文件在res/xml文件夹下;
  2、这个文件的名字是“updatelog.xml”
  3、这是一个xml文件
  
  


  2、在代码中调用方法如下:
  public class ResourcesActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView( R.layout.resources_layout );
  mTextView = ( TextView )findViewById( R.id.textId );
  getFileResources( );
  }

  private void getFileResources( ){
  String packageName = getPackageName( );
  try {
  Resources resources = this.getPackageManager( ).getResourcesForApplication( packageName );
  int resId = resources.getIdentifier( "updatelog", "xml", packageName );
  String log = getUpdatelog( resId, resources );

  int appId = resources.getIdentifier( "action_settings", "string", packageName );
  String appName = resources.getString( appId );

  mTextView.setText( appName + "\n" + log );
  } catch (NameNotFoundException e) {
  e.printStackTrace();
  }
  }

  private String parseTag( XmlResourceParser xml ) throws XmlPullParserException, IOException {
  String result = "Version: "+ xml.getAttributeValue(null, "version") + "\n" + "VersionCode: " + xml.getAttributeValue(null, "versioncode") + "\n";
  int eventType = xml.getEventType( );
  while( ( eventType != XmlPullParser.END_TAG ) || ( xml.getName( ).equals( "log" ) ) ) {
  if( (eventType == XmlPullParser.START_TAG) && ( xml.getName( ).equals( "log" ) ) ) {
  eventType = xml.next( );
  result = result + xml.getText( ) + "\n";
  }
  eventType = xml.next( );
  }

  return result;
  }

  private String getUpdatelog( int resourceId, Resources resource ) {
  String result = "";
  XmlResourceParser xmlResParser = resource.getXml( resourceId );
  try {
  int eventType = xmlResParser.getEventType( );
  while ( eventType != XmlPullParser.END_DOCUMENT ) {
  if ( ( eventType == XmlPullParser.START_TAG ) && ( xmlResParser.getName( ).equals( "release" ) ) ) {
  result = result + parseTag( xmlResParser );

  }
  eventType = xmlResParser.next( );
  }
  } catch (XmlPullParserException e) {
  System.out.println( e.getMessage( ) );
  } catch (IOException e) {
  System.out.println( e.getMessage( ) );
  } finally {
  xmlResParser.close( );
  }

  return result;
  }

  private TextView mTextView = null;
  }