Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】XmlPullParserを使ってXMLを解析する方法をステップ別に解説

XmlPullParserとは

XmlPullParserは、Androidに標準で組み込まれているXMLパーサーです。イベント駆動型(プル型)の解析方式を採用しており、XMLドキュメントを先頭から順に読み進めながら「開始タグ」「テキスト」「終了タグ」といったイベントを一つずつ処理していきます。DOMのようにドキュメント全体をメモリ上に展開しないため、省メモリかつ高速に動作し、リソースが限られたモバイル環境でのXML解析に最適です。

本記事では、XmlPullParserを使ってユーザー情報が記述されたXMLファイルを解析し、その結果をListViewに表示するサンプルアプリの作成手順を、ステップごとにわかりやすく解説します。


ステップ1:新しいプロジェクトを作成する

Android Studioを起動し、メニューから「File」⇒「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。

ステップ2:activity_main.xml にコードを追加する

res/layout/activity_main.xml に以下のコードを記述します。ここには、解析したXMLデータの一覧を表示するためのListViewを配置しています。

<?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>

ステップ3:リスト項目用のレイアウトファイルを作成する

res/layout フォルダを右クリックして、新しいレイアウトリソースファイル「row.xml」を作成し、以下のコードを追加します。このレイアウトには、名前・役職・所在地を表示するための3つのTextViewを配置しています。

<?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="17sp" />
    <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="14sp" />
    <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="14sp" />
</RelativeLayout>

ステップ4:MainActivity.java にパース処理を実装する

src/MainActivity.java に以下のコードを記述します。XmlPullParserFactoryからパーサーのインスタンスを取得し、getEventType()next()を使ってイベントを順番に処理していくのが実装のポイントです。「user」タグの開始を検知したら新しいHashMapを生成し、「name」「designation」「location」の各終了タグで値を格納。「user」タグの終了時にリストへ追加することで、複数ユーザーのデータをまとめて取得できます。

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();
        }
    }
}

ステップ5:解析対象のXMLファイルを用意する

assetsフォルダを作成し、その中に「userdetails.xml」というAndroidリソースファイルを追加して、以下の内容を記述します。ここには、名前・役職・所在地を持つ3人分のユーザーデータを定義しています。

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

ステップ6:AndroidManifest.xml にコードを追加する

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>

アプリを実行して結果を確認する

それでは、アプリを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続していることを前提とします。Android Studioからアプリを起動するには、プロジェクト内のいずれかのアクティビティファイルを開き、ツールバーにある「Run(実行)」アイコンをクリックします。表示された選択肢から自分のモバイル端末を選択すると、端末の画面にXMLを解析した結果の一覧が表示されます。

【Android】XmlPullParserを使ってXMLを解析する方法をステップ別に解説

  1. AndroidでJSONObjectを使ってJSONを解析する方法をわかりやすく解説

    はじめにこの記事では、Androidアプリ開発においてJSONObjectクラスを使用してJSONデータを解析(パース)する方法を、実際のコード例とともにステップごとに解説します。JSONはWeb APIなどで広く使われるデータ形式であり、Android開発では必須の知識です。手順1:新しいプロジェクトを作成するAndroid Studioを開き、File → New Projectを選択して新しいプロジェクトを作成します。必要な項目をすべて入力してプロジェクトのセットアップを完了させてください。手順2:レイアウトファイル(activity_main.xml)を編集するres/layout/a

  2. 【Android開発】Volleyライブラリを使ってJSONを解析する方法をステップ解説

    Volleyライブラリとは この記事では、AndroidアプリでVolleyライブラリを使用してJSONデータを解析(パース)する方法を、ステップごとにわかりやすく解説します。VolleyはGoogleが提供するHTTP通信ライブラリで、ネットワークリクエストの管理やJSONの取得・解析を少ないコード量で実現できるのが特徴です。 ステップ1:新規プロジェクトの作成 まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを生成してください。 ステップ2:レイアウトファイル(act