Skip to content

Instantly share code, notes, and snippets.

@anon5r
Created April 23, 2017 14:52
Show Gist options
  • Select an option

  • Save anon5r/8394af8a92b26604ed4ded25029f99e2 to your computer and use it in GitHub Desktop.

Select an option

Save anon5r/8394af8a92b26604ed4ded25029f99e2 to your computer and use it in GitHub Desktop.
アプリのリソースファイル内に置いたXMLファイルをパースして使用するときのサンプル
package net.anoncom.android.example;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.res.Resources;
import android.util.Log;
public class XmlSample {
public static void loadXML() {
try {
XmlPullParser parser = getResources().getXml(R.xml.target);
try {
parser.setInput(getResources().openRawResource(R.xml.target), null);
} catch (NotFoundException e) {
Log.e("XML_ERROR", e.getMessage());
} catch (XmlPullParserException e) {
Log.e("XML_ERROR", e.getMessage());
}
for(int e = parser.getEventType(); e != XmlPullParser.END_DOCUMENT; e = parser.next()) {
keyword = new Keyword();
if(e == XmlPullParser.START_DOCUMENT) {
// ドキュメント開始
Log.d("XML:DOC", "START");
} else if( e == XmlPullParser.TEXT ) {
// エレメントに囲まれている部分
Log.d("XML:TEXT", parser.getText());
} else if(e == XmlPullParser.START_TAG) {
// エレメントの開始
Log.d("XML:ELEM", "START");
// エレメント名
Log.d("XML:ELEM_NAME", parser.Name());
for( int a = 0; a < parser.getAttributeCount(); a++ ) {
// 属性情報
Log.d("XML:ELEM_ATTR", parser.getAttributeName(a) + " = " + parser.getAttributeValue(a));
}
} else if(e == XmlPullParser.END_TAG) {
// エレメントの終了
Log.d("XML:ELEM", "END");
}
}
if ( e == XmlPullParser.END_DOCUMENT ) {
// ドキュメント終了
Log.d("XML:DOC", "END");
}
} catch (NotFoundException e) {
Log.e("XML", e.getClass().getName() + ": " + e.getMessage());
} catch ( XmlPullParserException e) {
Log.d( "XML", e.getClass().getName() + ": " + e.getMessage() );
for ( StackTraceElement s : e.getStackTrace()) {
Log.d( "TRACE", s.toString());
}
} catch ( IOException e) {
Log.d( "XML", e.getClass().getName() + ": " + e.getMessage() );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment