Computer >> Máy Tính >  >> Lập trình >> Android

Cách sử dụng XMLPullParser để phân tích cú pháp XML trong Android?


Ví dụ này trình bày cách sử dụng XMLPullParser trong android.

Bước 1 - Tạo một dự án mới trong Android Studio, đi tới Tệp ⇒ Dự án Mới và điền tất cả các chi tiết cần thiết để tạo một dự án mới.

Bước 2 - Thêm mã sau vào res / layout / activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >
   <ListView
      android:id="@+id/listView"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:dividerHeight="1dp" />
</LinearLayout>

Bước 3 - Nhấp chuột phải vào res / layout và tạo tệp tài nguyên bố cục (row.xml) và thêm mã sau -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:padding="5dip" >
   <TextView
      android:id="@+id/tvName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textStyle="bold"
      android:textSize="17dp" />
   <TextView
      android:id="@+id/tvDesignation"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@id/tvName"
      android:layout_marginTop="7dp"
      android:textColor="#343434"
      android:textSize="14dp" />
   <TextView
      android:id="@+id/tvLocation"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignBaseline="@+id/tvDesignation"
      android:layout_alignBottom="@+id/tvDesignation"
      android:layout_alignParentRight="true"
      android:textColor="#343434"
      android:textSize="14dp" />
</RelativeLayout>

Bước 4 - Thêm mã sau vào src / MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      try {
         ArrayList<HashMap<String, String>> userList = new ArrayList<>();
         HashMap<String,String> user = new HashMap<>();
         ListView lv = findViewById(R.id.listView);
         InputStream inputStream = getAssets().open("userdetails.xml");
         XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
         XmlPullParser parser = parserFactory.newPullParser();
         parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES,false);
         parser.setInput(inputStream,null);
         String tag = "" , text = "";
         int event = parser.getEventType();
         while (event!= XmlPullParser.END_DOCUMENT){
            tag = parser.getName();
            switch (event) {
               case XmlPullParser.START_TAG:
                  if(tag.equals("user"))
                     user = new HashMap<>();
               break;
               case XmlPullParser.TEXT:
                  text=parser.getText();
               break;
               case XmlPullParser.END_TAG:
               switch (tag) {
                  case "name": user.put("name",text);
                  break;
                  case "designation": user.put("designation",text);
                  break;
                  case "location": user.put("location",text);
                  break;
                  case "user":
                  if(user!=null)
                     userList.add(user);
                  break;
               }
               break;
            }
            event = parser.next();
         }
         ListAdapter adapter = new SimpleAdapter(MainActivity.this, userList, R.layout.row,
         new String[]{"name","designation","location"}, new int[]{R.id.tvName,
         R.id.tvDesignation, R.id.tvLocation});
         lv.setAdapter(adapter);
      }
      catch (IOException e) {
         e.printStackTrace();
      } catch (XmlPullParserException e) {
         e.printStackTrace();
      }
   }
}

Bước 5 - Tạo một thư mục tài sản, bên trong thư mục tài sản tạo một tệp tài nguyên android (userdetails.xml) và thêm phần sau

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <users>
      <user>
         <name>Sehwag</name>
         <designation>Vice Captain</designation>
         <loation>Delhi</loation>
      </user>
      <user>
         <name>Ashwin</name>
         <designation>Off Spin Bowler</designation>
         <loation>Chennai</loation>
      </user>
      <user>
         <name>Dhoni</name>
         <designation>Captain</designation>
         <loation>Ranchi</loation>
      </user>
   </users>
</resources>

Bước 6 - Thêm mã sau vào androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Hãy thử chạy ứng dụng của bạn. Tôi giả sử bạn đã kết nối thiết bị Di động Android thực tế với máy tính của mình. Để chạy ứng dụng từ android studio, hãy mở một trong các tệp hoạt động của dự án của bạn và nhấp vào biểu tượng Chạy từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn, sau đó kiểm tra thiết bị di động sẽ hiển thị màn hình mặc định của bạn -

Cách sử dụng XMLPullParser để phân tích cú pháp XML trong Android?