最もよく使われているスマートフォン・プラットフォームである Android は、スマートフォンでも、モバイル・タブレットでも機能します。例えば、Motorola XOOM は
Android タブレットです。この記事を読んで、Android 機器上で XML 文書の作成と構文解析を行う方法を学んでください。XML を出力するには、標準 javax.xml.transform.Transformer クラスを使用することができます。Android で XML を構文解析するには、DOM パーサー、SAX パーサーを使用できる他、org.xmlpull.v1.XmlPullParser というプル・パーサーも XML の構文解析手段として使用することができます。この記事の例では、Android 3.0 プラットフォームで XML を処理します。
この記事で使用しているサンプル・アプリケーションは、「ダウンロード」セクションからダウンロードしてください。
この記事の例に従うには、以下のソフトウェアをインストールして構成してください。各ソフトウェアに関しては、「参考文献」のリンクを参照してください。
- Eclipse IDE をインストールします。
- Eclipse 用の Android Development Tools (ADT) プラグインをインストールします。ADT は、Eclipse での Android アプリケーション開発を可能にする一連の拡張機能を提供します。
- Android SDK Platform をダウンロードしてインストールします。Android SDK Platform は、Android アプリケーションの開発ツールを提供するプラットフォームです。
- Eclipse で、「Window (ウィンドウ)」 > 「Android SDK and AVD Manager (Android SDK および AVD マネージャー)」の順に選択し、Android SDK and AVD Manager (Android SDK および AVD マネージャー) を起動します。
- Android SDK and AVD Manager で、AVD (Android Virtual Device) を作成します。AVD は、Android
のエミュレーターです。
AVD では、「Platform (プラットフォーム)」として「3.0」を、「API Level (API レベル)」として「11」を選択します。
このセクションでは、Android で XML 文書を作成します。最初のステップとして、まずは Android プロジェクトを作成します。
- Eclipse IDE で「File (ファイル)」 > 「New (新規)」 > 「Other (その他)」の順に選択します。「New (新規)」ダイアログで「Android」 > 「Android Project (Android プロジェクト)」の順に選択し、「Next (次へ)」をクリックします。
- 「New Android Project (新規 Android プロジェクト)」ウィンドウ (図 1 を参照) で、以下の情報を指定します。
- 「Project name (プロジェクト名)」: 「
CreatingXML」 - 「Build Target (ビルド・ターゲット)」チェック・ボックス: 「Android 3.0」(「Platform (プラットフォーム)」: 「3.0」、「API Level (API レベル)」: 「11」)
- 「Properties (プロパティー)」:
- 「Application name (アプリケーション名)」: 「
CreatingXML」 - 「Package name (パッケージ名)」: 「
android.xml」 - 「Create Activity (アクティビティーの作成)」:
このチェック・ボックスを選択し、アクティビティー・クラスとして「
CreatingXML」を指定します。アクティビティーは、ユーザー操作を表します。Activityクラスを継承するこのクラスが、UI のウィンドウを作成します。 - 「Min SDK Version (最小 SDK バージョン)」: 「11」
- 「Application name (アプリケーション名)」: 「
図 1. Android 3.0 プラットフォーム用の Android プロジェクトの作成
- 「Project name (プロジェクト名)」: 「
- 「Next (次へ)」をクリックします。
- 「Finish (完了)」をクリックします。これで、XML 文書を作成するための Android プロジェクトが作成されます。Android プロジェクトは、以下のファイルで構成されます。
CreatingXMLアクティビティー・クラス。このクラスが、Activity クラスを継承します。- res/layout/main.xml ファイル。Android UI コンポーネントのレイアウトを指定するファイルです。
- AndroidManifest.xml ファイル。このファイルには、パッケージ名、Android アプリケーション起動時に呼び出されるメイン・アクティビティー、アプリケーション・コンポーネント、プロセス、アクセス許可、最小 API レベルなどのアプリケーション構成が記されています。
図 2 に、CreatingXML Android プロジェクトのディレクトリー構造を示します。
図 2. XML 文書を作成するためのAndroid プロジェクト
res/layout/main.xml ファイルに、Android UI コンポーネントのレイアウトを指定します。LinearLayout を作成して、android:orientation を
“vertical” に設定します。この例では、XML 文書をテキスト・メッセージとして表示します。したがって、XML
文書を表示するために、id を xmlresult に設定した TextView 要素を追加します (リスト 1 を参照)。
リスト 1. main.xml レイアウト・ファイル
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/xmlresult" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
|
AndroidManifest.xml ファイルには、実行するアクティビティーとして CreatingXML
を指定します。uses-sdk 要素で、最小 Android バージョンを 11 に指定し、activity
要素のサブ要素として intent-filter を指定し、さらにそのサブ要素として action を指定します。リスト 2 にこのファイルを記載します。
リスト 2. AndroidManifest.xml 構成ファイル
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.xml"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="11" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CreatingXML"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
|
いよいよ、Activity クラスを継承する CreatingXML アクティビティー・クラスの中で XML 文書を作成します。この例では javax.xml.parsers.DocumentBuilder を使用して XML 文書を作成するので、以下のクラスやパッケージをインポートする必要があります。
javax.xml.parsers.DocumentBuilderクラスjavax.xml.parsers.DocumentBuilderFactoryクラスorg.w3c.domパッケージjavax.xml.transform.TransformerFactoryクラスjavax.xml.transform.Transformerクラスjavax.xml.transform.dom.DOMSourceクラスjavax.xml.transform.stream.StreamResultクラス
CreatingXML アクティビティーが開始されると、onCreate(Bundle
savedInstanceState) メソッドが呼び出されます。onCreate メソッドでは
setContentView メソッドを使用して UI を設定します。具体的には、setContentView(R.layout.main); によってレイアウト・リソースを設定します。
findViewById メソッドを使用して、main.xml ファイルに、Android ウィジェットである
TextView オブジェクを定義します。そのためのコードは、TextView xmlResult =
(TextView) findViewById(R.id.xmlresult); です。このように、オブジェクトの id は、xmlresult に設定します。
static メソッド newInstance() を使用して、DocumentBuilderFactory
オブジェクトのインスタンスを作成します。DocumentBuilder オブジェクトを作成するには、DocumentBuilderFactory クラスの newDocumentBuilder() メソッドを使用します (リスト 3 を参照)。
リスト 3. DocumentBuilder の作成
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); |
XML 文書は DOM 構造によって表現されます。新規 Document オブジェクトを作成するには、DocumentBuilder クラスの newDocument()
メソッドを使用して、Document document = documentBuilder.newDocument(); というコードを作成します。
createElement() メソッドを使用した Element rootElement =
document.createElement("catalog");
というコードで Document オブジェクトのルート要素 “catalog” を作成します。
setAttribute メソッドを使用して、ルート要素に “publisher” 属性と “journal” 属性を設定します (リスト 4 を参照)。
リスト 4. ルート要素の属性の設定
rootElement.setAttribute("journal", "Oracle Magazine");
rootElement.setAttribute("publisher", "Oracle Publishing");
|
appendChild() メソッドを使用して、ルート要素を Document オブジェクトに追加します。そのためのコードは、document.appendChild(rootElement); です。
createElement() メソッドを使用して “article” 要素作成し、この要素を appendChild()
メソッドを使ってルート要素に追加します (リスト 5 を参照)。
リスト 5. “article” 要素の作成
Element articleElement = document.createElement("article");
rootElement.appendChild(articleElement);
|
“article” 要素に “edition” 要素を追加します (リスト 6 を参照)。
リスト 6. “edition” 要素の追加
Element editionElement = document.createElement("edition");
articleElement.appendChild(editionElement);
|
“edition” 要素には、createTextNode()
メソッドを使用してテキスト・ノードを追加します。editionElement.appendChild(document.createTextNode("Sept-Oct 2005")); として、テキスト・ノードの値を “Sept-Oct 2005” に設定します。
同じようにして、”title” 要素を作成して “article”
要素に追加します。リスト 7 に示すように、”title” 要素にテキスト・ノードを追加し、テキスト・ノードの値を
“Creating Search Pages” に設定します。
リスト 7. テキスト・ノードの作成
Element titleElement = document.createElement("title");
articleElement.appendChild(titleElement);
titleElement.appendChild(document.createTextNode("Creating Search Pages"));
|
“article” 要素に “author”
要素を追加し、”author” 要素にテキスト・ノードを追加します。このテキスト・ノードの値は “Steve Muench” に設定します (リスト 8 を参照)。
リスト 8. “author” 要素の追加
authorElement = document.createElement("author");
articleElement.appendChild(authorElement);
authorElement.appendChild(document.createTextNode("Steve Muench"));
|
別の “article” 要素をルート要素に追加します。XML 文書の DOM 構造は、Android 以外のアプリケーションの場合と同じ方法で作成することができます。例えば、以下のようにします。
- DOM の
DocumentオブジェクトをByteArrayOutputStreamに出力します。 - この
OutputStreamから、XML 文書をストリングとして取得します。 - 取得したストリングを Android の
TextViewウィジェットに設定します。
static メソッド newInstance() を使用して、TransformerFactory オブジェクトを作成し、factory オブジェクトの newTransformer()
メソッドを使用して、Transformer オブジェクトを作成します (リスト
9 を参照)。
リスト 9. Transformer オブジェクトの作成
TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); |
java.util.Properties オブジェクトを作成し、以下の出力プロパティーを設定します。
- インデント (
INDENT) - 出力フォーマット (
METHOD) - XML 宣言 (
OMIT_XML_DECLARATION) - XML バージョン (
VERSION) - XML 文書のエンコード (
ENCODING)
DOM 構造を変換するには、Source オブジェクトと Result オブジェクトが必要です。そこで、Document オブジェクトから DOMSource オブジェクトを作成し、出力として、ByteArrayOutputStream から ByteArrayOutputStream と StreamResult
オブジェクトを作成します (リスト 10 を参照)。
リスト 10. DOM 構造の変換
DOMSource domSource = new DOMSource(document.getDocumentElement()); OutputStream output = new ByteArrayOutputStream(); StreamResult result = new StreamResult(output); |
Transformer オブジェクトの transform()
メソッドを使用して、Document オブジェクトを変換します。そのためのコードは、transformer.transform(domSource, result); です。
ByteArrayOutputStream オブジェクトから String オブジェクトを取得し、その String を TextView ウィジェットの xmlResult に設定します。
リスト 11. String の取得および設定
String xmlString = output.toString(); xmlResult.setText(xmlString); |
リスト 12 に、Activity クラスを継承する CreatingXML アクティビティー・クラスを示します。
リスト 12. Activity クラスを継承する
CreatingXML アクティビティー・クラス
package android.xml;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import javax.xml.transform.dom.DOMSource;
public class CreatingXML extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView xmlResult = (TextView) findViewById(R.id.xmlresult);
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory
.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("catalog");
rootElement.setAttribute("journal", "Oracle Magazine");
rootElement.setAttribute("publisher", "Oracle Publishing");
document.appendChild(rootElement);
Element articleElement = document.createElement("article");
rootElement.appendChild(articleElement);
Element editionElement = document.createElement("edition");
articleElement.appendChild(editionElement);
editionElement.
appendChild(document.createTextNode("Sept-Oct 2005"));
Element titleElement = document.createElement("title");
articleElement.appendChild(titleElement);
titleElement.appendChild(document
.createTextNode("Creating Search Pages"));
Element authorElement = document.createElement("author");
articleElement.appendChild(authorElement);
authorElement.
appendChild(document.createTextNode("Steve Muench"));
articleElement = document.createElement("article");
rootElement.appendChild(articleElement);
editionElement = document.createElement("edition");
articleElement.appendChild(editionElement);
editionElement.appendChild(document
.createTextNode("November - December 2010"));
titleElement = document.createElement("title");
articleElement.appendChild(titleElement);
titleElement.appendChild(document
.createTextNode("Agile Enterprise Architecture"));
authorElement = document.createElement("author");
articleElement.appendChild(authorElement);
authorElement.appendChild(document.createTextNode("Bob Rhubart"));
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
Properties outFormat = new Properties();
outFormat.setProperty(OutputKeys.INDENT, "yes");
outFormat.setProperty(OutputKeys.METHOD, "xml");
outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
outFormat.setProperty(OutputKeys.VERSION, "1.0");
outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperties(outFormat);
DOMSource domSource =
new DOMSource(document.getDocumentElement());
OutputStream output = new ByteArrayOutputStream();
StreamResult result = new StreamResult(output);
String xmlString = output.toString();
xmlResult.setText(xmlString);
} catch (ParserConfigurationException e) {
} catch (TransformerConfigurationException e) {
} catch (TransformerException e) {
}
}
} |
これで、Android アプリケーションを実行できる状態になりました。CreatingXML アプリケーション・ノードを右クリックして、「Run As (実行)」 > 「Android Application (Android アプリケーション)」の順に選択します (図 3 を参照)。
図 3. Android アプリケーションの実行
Android AVD が起動され、Android アプリケーションが Android AVD にデプロイされます (図 4 を参照)。
図 4. Android 機器にインストールされた CreatingXML アプリケーション
CreatingXML アプリケーションのアイコンをクリックすると、このアプリケーションのアクティビティーが起動され、XML 文書が作成されて Android 機器に表示されます (図 5 を参照)
図 5. Android 機器で作成および表示された XML 文書
このセクションでは、XML 文書を構文解析する方法を説明します。XML 文書の構文解析には標準の DOM パーサーおよび SAX パーサーの他、別のパーサーも使用することができます。この例では、org.xmlpull.v1.XmlPullParser を使用して、リスト 13 に記載する XML 文書 catalog.xml の構文解析を行います。
リスト 13. catalog.xml
<?xml version = '1.0' encoding = 'UTF-8'?>
<catalog journal="Oracle Magazine" publisher="Oracle Publishing">
<article>
<edition>Sept-Oct 2005</edition>
<title>Creating Search Pages</title>
<author>Steve Muench</author>
</article>
<article>
<edition>November - December 2010</edition>
<title>Agile Enterprise Architecture</title>
<author>Bob Rhubart</author>
</article>
</catalog>
|
XML 文書を構文解析するには、前の「XML 文書の作成」セクションでの場合と同じく、Android プロジェクトを作成する必要があります。
- Eclipse IDE で「File (ファイル)」 > 「New (新規)」 > 「Other (その他)」の順に選択します。「New (新規)」ダイアログで「Android」 > 「Android Project (Android プロジェクト)」の順に選択し、「Next (次へ)」をクリックします。
- 「New Android Project (新規 Android プロジェクト)」ウィンドウ (図 6 を参照) で、以下の情報を指定します。
- 「Project name (プロジェクト名)」: 「
ParsingXML」 - 「Build Target (ビルド・ターゲット)」チェック・ボックス: 「Android 3.0」(「Platform (プラットフォーム)」: 「3.0」、「API Level (API レベル)」: 「11」)
- プロパティー:
- 「Application name (アプリケーション名)」: 「
ParsingXML」 - 「Package name (パッケージ名)」: 「
android.xml」 - 「Create Activity (Activity の作成)」:
このチェック・ボックスを選択し、アクティビティー・クラスとして「
ParsingXML」を指定します。 - 「Min SDK Version (最小 SDK バージョン)」: 11
- 「Application name (アプリケーション名)」: 「
図 6. XML 文書を構文解析するための Android プロジェクトの作成
- 「Project name (プロジェクト名)」: 「
- 「Finish (完了)」をクリックします。
これにより、Android プロジェクトが作成されます。その構成内容は以下のとおりです。
Activityクラスを継承するアクティビティー・クラスParsingXML- レイアウトを指定する res/layout/main.xml ファイル
- アプリケーション構成が記される AndroidManifest.xml ファイル
XML 文書を構文解析し、ラベルを使用して要素の値を出力します。ラベルと要素のテキスト・ノードの値は TextView ウィジェットに出力されます。
- main.xml ファイルで、各ラベルおよび各要素のテキスト・ノードの値に
TextViewウィジェットを追加します。 LinearLayoutを作成して、android:orientationを“vertical”に設定します。- 以下の id を持つ
TextView要素を追加します。"journal_label""journal""publisher_label""publisher""edition1_label""edition1""title1_label""title1""author1_label""author1""edition2_label""title2_label""title2""author2_label""author2"
リスト 14 に main.xml ファイルを記載します。
リスト 14. main.xml レイアウト・ファイル
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/journal_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Journal:" />
<TextView android:id="@+id/journal" android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/publisher_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Publisher:" />
<TextView android:id="@+id/publisher"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/edition1_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Edition:" />
<TextView android:id="@+id/edition1" android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/title1_label"
android:layout_height="wrap_content" android:text="Title:" />
<TextView android:id="@+id/title1"
android:singleLine="true" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/author1_label"
android:layout_height="wrap_content" android:text="Author:" />
<TextView android:id="@+id/author1" android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/edition2_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Edition:" />
<TextView android:id="@+id/edition2" android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/title2_label"
android:layout_height="wrap_content" android:text="Title:" />
<TextView android:id="@+id/title2"
android:singleLine="true" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/author2_label"
android:layout_height="wrap_content" android:text="Author:" />
<TextView android:id="@+id/author2" android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
|
AndroidManifest.xml ファイルには、以下の情報を指定します。
- 実行する
アクティビティーとしてParsingXMLを指定します。 uses-sdk要素で最小 Android バージョンとして 11 を指定します。- activity 要素とそのサブ要素として、
activity、intent-filter、actionを指定します。
リスト 15 に、完成した AndroidManifest.xml ファイルを記載します。
リスト 15. AndroidManifest.xml 構成ファイル
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.xml"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="11" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ParsingXML"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
|
XML 文書リソースを構文解析するためにこの例で使用するのは、XmlPullParser インターフェースを継承する android.content.res.XmlResourceParser です。まず、res ディレクトリー内に XML 文書用のディレクトリーを作成する必要があります。
- res ディレクトリー内に xml という名前のディレクトリーを作成します。この res/xml ディレクトリーに、XML 文書 catalog.xml をコピーします。
ParsingXMLアクティビティー・クラスに android.content.res.XmlResourceParser および org.xmlpull.v1.XmlPullParser インターフェースをインポートします。このアクティビティーが起動されると、
onCreate(Bundle savedInstanceState)メソッドが呼び出されます。onCreateメソッドには、setContentViewメソッドを使用して UI を設定し、setContentView(R.layout.main);を使用してレイアウト・リソースを設定します。- main.xml ファイルに定義された Android
TextViewウィジェットを取得します。それには、findViewByIdメソッドとそれぞれのウィジェットの id を使用します (リスト 16 を参照)。
リスト 16. TextView ウィジェットの取得
TextView journal = (TextView) findViewById(R.id.journal); TextView publisher = (TextView) findViewById(R.id.publisher); TextView edition1 = (TextView) findViewById(R.id.edition1); TextView title1 = (TextView) findViewById(R.id.title1); TextView author1 = (TextView) findViewById(R.id.author1); TextView edition2 = (TextView) findViewById(R.id.edition2); TextView title2 = (TextView) findViewById(R.id.title2); TextView author2 = (TextView) findViewById(R.id.author2); |
res/xml ディレクトリーの catalog.xml 文書から、XmlResourceParser
オブジェクトを作成します。そのためのコードは、XmlResourceParser xpp =
getResources().getXml(R.xml.catalog); です。
XML 文書の構文解析には、XmlResourceParser を使用します。これも同じくプル・パーサーです
(このパーサーは XmlPullParser インターフェースを継承します)。プル・パーサーでは、XML
文書は一連の構文解析イベントに過ぎません。次の構文解析イベントを取得するには、next() メソッドを使用して
xpp.next(); というコードを作成します。
getEventType メソッドを使用して、イベント・タイプを取得します。このメソッドにより、int 型の値が返されます。このコードは、int eventType =
xpp.getEventType(); のようになります。
返される int には、表 1 に記載する値のいずれかが含まれます。
表 1.
int 型のイベント・タイプの値| int 型の値 | 説明 |
|---|---|
| COMMENT | XML についてのコメント |
| DOCDECL | XML 文書タイプの宣言 |
| END_DOCUMENT | 文書の終わり |
| END_TAG | 要素タグの終わり |
| IGNORABLE_WHITESPACE | 無視できるホワイト・スペース |
| PROCESSING_INSTRUCTION | 処理命令 |
| START_DOCUMENT | 文書の始まり |
| START_TAG | 要素タグの始まり |
| TEXT | 文字データ |
この XML
文書で構文解析対象となるのは、要素と要素のテキスト・ノードだけです。属性はイベントを生成しません。したがって、属性は要素から取得することができます。イベント・タイプには、START_TAG と TEXT しかないはずです。この 2
つは、要素の開始タグ、要素のテキスト・ノードにそれぞれ対応します。まず、要素タグを判別し、それからその要素タグのテキスト・ノード値を取得します。XML 文書内のさまざまな
“article” 要素を示すには、int 型の変数 iter を使用し、要素タグの名前を指定するには String 型の変数 elemtext を使用します。イテレーターの int 変数と、要素名の String 変数を指定するには、リスト 17 に記載するコードを使用します。
リスト 17. 変数の指定
int iter = 0; String elemtext = null; |
XML 文書の終わりに達するまでに、以下の操作を実行します。
- イベント・タイプを判別します。
- 要素タグの名前と要素タグのテキスト値を取得します。
- テキスト・ノードの値を対応する
TextViewウィジェットに設定します。
例えば、特定の要素タグの名前を取得するには、リスト 18 のコードを使用します。
リスト 18. 開始タグの要素名の取得
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String elemName = xpp.getName();
...
...
}
}
|
要素タグの名前が “catalog” の場合には、“journal” および “publisher”
の属性値を取得し、これらの属性値をTextView ウィジェット “journal” および “publisher” に設定します。属性値を取得するには、XmlResourceParser の getAttributeValue() メソッドを使用します (リスト 19 を参照)。
リスト 19. 属性値の取得および設定
if (elemName.equals("catalog")) {
String journalAttr = xpp.getAttributeValue(null,"journal");
String publisherAttr = xpp.getAttributeValue(null,"publisher");
journal.setText(journalAttr);
publisher.setText(publisherAttr);
...
}
|
各 “article” 要素のイテレーター変数 iter
をインクリメントします (リスト 20 を参照)。
リスト 20. 変数のインクリメント
if (elemName.equals("article")) {
iter = iter + 1;
}
|
イベント・タイプが TEXT であれば、テキスト・ノードの値を取得し、その値を対応する TextView ウィジェットに設定します。要素タグの名前を取得するには、イベント・タイプ START_TAG に設定した String
変数 elemtext を使用します。テキスト・ノードの値を取得するには、XmlResourceParser の
getText() メソッドを使用します。取得したテキスト・ノードの値は、setText メソッドを使用して
TextView ウィジェットに設定します (リスト 21 を参照)。
リスト 21. テキスト・ノード値の取得
else if (eventType == XmlPullParser.TEXT) {
//Obtain the element name and element text node values and
//set the text node values on the corresponding TextView
//widgets
}
|
リスト 22 に、Activity
クラスを継承するアクティビティー・クラス ParsingXML を示します。
リスト 22. Activity クラスを継承するアクティビティー・クラス ParsingXML
package android.xml;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import android.content.res.XmlResourceParser;
public class ParsingXML extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(R.layout.relativelayout);
TextView journal = (TextView) findViewById(R.id.journal);
TextView publisher = (TextView) findViewById(R.id.publisher);
TextView edition1 = (TextView) findViewById(R.id.edition1);
TextView title1 = (TextView) findViewById(R.id.title1);
TextView author1 = (TextView) findViewById(R.id.author1);
TextView edition2 = (TextView) findViewById(R.id.edition2);
TextView title2 = (TextView) findViewById(R.id.title2);
TextView author2 = (TextView) findViewById(R.id.author2);
try {
XmlResourceParser xpp = getResources().getXml(R.xml.catalog);
xpp.next();
int eventType = xpp.getEventType();
int iter = 0;
String elemtext = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String elemName = xpp.getName();
if (elemName.equals("catalog")) {
String journalAttr = xpp.getAttributeValue(null,
"journal");
String publisherAttr = xpp.getAttributeValue(null,
"publisher");
journal.setText(journalAttr);
publisher.setText(publisherAttr);
}
if (elemName.equals("article")) {
iter = iter + 1;
}
if (elemName.equals("edition")) {
elemtext = "edition";
}
if (elemName.equals("title")) {
elemtext = "title";
}
if (elemName.equals("author")) {
elemtext = "author";
}
}
else if (eventType == XmlPullParser.TEXT) {
if (iter == 1) {
if (elemtext.equals("edition")) {
edition1.setText(xpp.getText());
} else if (elemtext.equals("title")) {
title1.setText(xpp.getText());
} else if (elemtext.equals("author")) {
author1.setText(xpp.getText());
}
}
else if (iter == 2) {
if (elemtext.equals("edition")) {
edition2.setText(xpp.getText());
} else if (elemtext.equals("title")) {
title2.setText(xpp.getText());
} else if (elemtext.equals("author")) {
author2.setText(xpp.getText());
}
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
} catch (IOException e) {
}
}
}
|
この Android アプリケーションを実行するには、ParsingXML アプリケーションを右クリックして、「Run As (実行)」 > 「Android Application (Android アプリケーション)」の順に選択します (図 7 を参照)。
図 7. XML 文書を構文解析する Android アプリケーションの実行
Android AVD が起動され、ParsingXML アプリケーションが Android 機器にインストールされます (図 8 を参照)。
図 8. Android 機器にインストールされた ParsingXML アプリケーション
ParsingXML アプリケーションをクリックすると、このアプリケーションのアクティビティーが起動され、XML 文書 catalog.xml が構文解析されて、Android 機器に出力されます (図 9 を参照)。
図 9. 構文解析によって取得された XML 文書ノードの値
上記では、要素のラベルと要素のテキスト・ノードが縦に並んでいますが、テキスト・ノードの値が対応するラベルの右側に配置されるレイアウトのほうが望ましいはずです。テキスト・ノードの値をラベルの右側に配置するカスタム・レイアウトにするには、LinearLayout
の代わりに RelativeLayout を使用します。そして、TextView ウィジェットの android:layout_marginLeft
属性を使用して、テキスト・ノードの値がラベルの右側に表示されるようにします。さらに、android:layout_below 属性を使用して、テキスト・ノードの値が前の行のテキスト・ノードの値の下に揃って表示されるようにします。
RelativeLayout にはこの他、ウィジェットを別のウィジェットの右側に出力する android:layout_toRightOf 属性、コンポーネントを別のコンポーネントの左側に出力する android:layout_toLeftOf 属性などもあります。リスト 23 に、相対配置レイアウトを使用した場合の main.xml を記載します。
リスト 23. 相対配置レイアウト
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5px">
<TextView android:id="@+id/journal_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Journal:" />
<TextView android:id="@+id/journal"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/publisher_label"
android:layout_below="@id/journal_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Publisher:" />
<TextView android:id="@+id/publisher"
android:layout_below="@id/journal"
android:layout_marginLeft="70px"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="@+id/edition1_label"
android:layout_below="@id/publisher_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Edition:" />
<TextView android:id="@+id/edition1"
android:layout_below="@id/publisher"
android:layout_width="fill_parent"
android:layout_marginLeft="50px"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/title1_label"
android:layout_below="@id/edition1_label"
android:layout_height="wrap_content"
android:text="Title:" />
<TextView android:id="@+id/title1"
android:layout_marginLeft="40px"
android:layout_below="@id/edition1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/author1_label"
android:layout_below="@id/title1_label"
android:layout_height="wrap_content"
android:text="Author:" />
<TextView android:id="@+id/author1"
android:layout_below="@id/title1"
android:layout_width="fill_parent"
android:layout_marginLeft="50px"
android:layout_height="wrap_content" />
<TextView android:id="@+id/edition2_label"
android:layout_below="@id/author1_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Edition:" />
<TextView android:id="@+id/edition2"
android:layout_below="@id/author1"
android:layout_width="fill_parent"
android:layout_marginLeft="50px"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@id/title2_label"
android:layout_below="@id/edition2_label"
android:layout_height="wrap_content"
android:text="Title:" />
<TextView android:id="@+id/title2"
android:layout_marginLeft="40px"
android:layout_below="@id/edition2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:layout_width="fill_parent"
android:id="@+id/author2_label"
android:layout_below="@id/title2_label"
android:layout_height="wrap_content"
android:text="Author:" />
<TextView android:id="@+id/author2"
android:layout_below="@id/title2"
android:layout_width="fill_parent"
android:layout_marginLeft="50px"
android:layout_height="wrap_content" />
</RelativeLayout>
|
レイアウトを修正したら、ParsingXML アプリケーションを再実行します。XML 文書が構文解析されて、指定されたレイアウトでノードの値が出力されます (図 10 を参照)。
図 10. フォーマット設定された XML 文書ノードの値
スマートフォンとモバイル・タブレットの両方に使用される Android 3.0 プラットフォームでは、XML
文書を作成し、構文解析することができます。この記事の例では、Android で標準の DocumentBuilder
およびトランスフォーマー API を使用して XML 文書を作成する方法、そしてXmlPullParser を継承する XMLResourceParser を使用して XML 文書を構文解析する方法を説明しました。
| 内容 | ファイル名 | サイズ | ダウンロード形式 |
|---|---|---|---|
| Android XML Eclipse application | android-xml-sourcecode.zip | 149KB | HTTP |
学ぶために
- Android: Android アプリケーションの作成方法を学んでください。
- 「Android で XML
を扱う」(Michael Galpin 著、developerWorks、2009年6月): Android での XML API について説明するこの記事で、独自の Android アプリケーションを構築する際に使用できる、Android で XML を扱うためのさまざまな方法を調べてください。
- 「Android と XML
を使って動的なユーザー・インターフェースを作成する」(Frank Ableson 著、developerWorks、2010年9月): Android 向けに、プログラマーでなくてもモバイル・ユーザーからデータを収集できる動的なユーザー・インターフェースを設計するための単純なアーキテクチャーについて学んでください。
- 「Android で XML と JSON
を使用する: 第 1 回 JSON と XML が Android アプリケーションにもたらすメリットを探る」(Frank Ableson 著、developerWorks、2010年8月): XML と JSON の基本、そしてこの 2 つのフォーマットで提供された Twitter のステータス更新フィードを構文解析して表示する Android アプリケーションを作成する方法を学んでください。
- 「Android で
XML と JSON を使用する: 第 2 回 JSON を使用してハイブリッド Android アプリケーションを実現する」(Frank Ableson 著、developerWorks、2010年8月): JavaScript、JSON、コールバック関数、Android-SDK Java コードを組み合わせて柔軟なモバイル・アプリケーションを構築する方法を探ってください。
- Android 関連の developerWorks コンテンツ: Android
に関する記事、デモ、チュートリアルを調べてください。
- この著者による他の記事
(Deepak Vohra 著、developerWorks、2005年4月から現在まで): Android、Ajax、PHP、XML、Web サービス、Ruby on Rails、EJB その他、さまざまな技術に関する記事を読んでください。
- New to XML で、XML を学ぶために必要なリソースを入手してください。
- developerWorks の XML エリア:
DTD、スキーマ、XSLT を含め、XML 分野でのスキルを磨くための資料を見つけてください。広範な技術に関する記事とヒント、チュートリアル、標準、そして IBM
レッドブックについては、XML ライブラリーを参照してください。
- IBM XML 認定: XML や関連技術の IBM 認定技術者になる方法について調べてください。
- developerWorks の Technical events and webcasts: これらのセッションで最新情報を入手してください。
- Twitter での developerWorks: 今すぐ登録して developerWorks のツイートをフォローしてください。
- developerWorks
podcasts: ソフトウェア開発者向けの興味深いインタビューとディスカッションを聞いてください。
- developerWorks オンデマンド・デモ: 初心者向けの製品のインストールおよびセットアップから熟練開発者向けの高度な機能に至るまで、さまざまに揃ったデモを見てください。
製品や技術を入手するために
- Android SDK: 最新のツールまたはプラットフォームを入手してください。
- Android Development Tools
(ADT): このプラグインをダウンロードして、Android アプリケーションを構築するための強力な統合環境を実現してください。
- JDK 6.0: パフォーマンスの改善およびバグ修正を含め、最新の Java リリースを入手してください。
- Eclipse for Java EE: 最新バージョンをダウンロードしてください。
- IBM 製品の評価版:
DB2、Lotus、Rational、Tivoli、および
WebSphere のアプリケーション開発ツールとミドルウェア製品を体験するには、評価版をダウンロードするか、IBM SOA Sandbox のオンライン試用版を試してみてください。
議論するために
- developerWorks
プロフィール: 今すぐ自分のプロフィールを作成して、Blogger Data API に関するウォッチ・リストをセットアップしてください。
- XML
ゾーンのディスカッション・フォーラム: XML 関連のフォーラムに参加してください。
- developerWorks コミュニティー: ここでは他の developerWorks ユーザーとのつながりを持てる他、開発者が主導するブログ、フォーラム、グループ、ウィキを調べることができます。