Bạn có thể dễ dàng phân tích tài liệu này và hiển thị nó cho người dùng trong ứng dụng của bạn khi hoc lập trình android. Một tài liệu RSS trông như thế này. Code: <rss version="2.0"> <channel> <title>Sample RSS</title> <link>http://www.google.com</link> <description>World's best search engine</description> </channel> </rss> 1. Phần tử RSS Một văn bản RSS như trên có các phần tử sau: STT Thành phần và mô tả 1 channel Nguyên tố này được sử dụng để mô tả các nguồn cấp dữ liệu RSS 2 title Xác định tiêu đề của kênh 3 link Xác định các siêu liên kết đến kênh 4 description Mô tả kênh 2. Phân tích cú pháp RSS Phân tích một tài liệu RSS là giống như phân tích cú pháp XML. Vì vậy, bây giờ cho phép xem làm thế nào để phân tích một tài liệu XML. Đối với điều này, chúng tôi sẽ tạo ra đối tượng XmlPullParser, nhưng để tạo ra rằng đầu tiên chúng ta sẽ tạo ra đối tượng XmlPullParserFactory và sau đó gọi phương pháp của nó newPullParser() để tạo ra XmlPullParser. Cú pháp của nó được đưa ra dưới đây private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance(); private XmlPullParser myparser = xmlFactoryObject.newPullParser(); Bước tiếp theo để nâng cấp file XmlPullParser bao gồm XML. Nó có thể là 1 file hoặc một Stream. Trogn trường hợp này, nó được đưa ra dưới đây: myparser.setInput(stream, null); Bước cuối cùng là phân tích những XML. Một file XML bao gồm các sự kiện, Name, Text, AttributesValue vv Vì vậy XmlPullParser có một chức năng riêng biệt để phân tích từng thành phần của tập tin XML. Cú pháp của nó được đưa ra dưới đây - Code: int event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.END_TAG: if(name.equals("temperature")){ temperature = myParser.getAttributeValue(null,"value"); } break; } event = myParser.next(); } Phương pháp getEventType trả về kiểu của sự kiện đó xảy ra. ví dụ:: Tài liệu bắt đầu, bắt đầu từ khóa e.t.c. Phương thức getName trả về tên của thẻ và vì chúng ta chỉ quan tâm đến nhiệt độ, vì vậy chúng tôi chỉ kiểm tra trong câu lệnh điều kiện rằng nếu chúng tôi đã nhận một thẻ nhiệt độ, chúng ta gọi phương thức getAttributeValue trở lại chúng ta giá trị của thẻ nhiệt độ. Ngoài các phương pháp này, có những phương pháp khác được cung cấp bởi lớp này cho các tập tin XML phân tích tốt hơn. Những phương pháp này được liệt kê dưới đây - STT Phương pháp và mô tả 1 getAttributeCount() Phương pháp này chỉ Trả về số các thuộc tính của thẻ bắt đầu hiện tại. 2 getAttributeName(int index) Phương pháp này trả về tên của thuộc tính được xác định bởi giá trị chỉ số. 3 getColumnNumber() Phương pháp này trả về Returns số cột hiện tại, bắt đầu từ 0. 4 getDepth() Phương thức này trả Returns độ sâu hiện tại của phần tử. 5 getLineNumber() Trả về số dòng hiện tại, bắt đầu từ 1. 6 getNamespace() Phương pháp này trả về không gian tên URI của phần tử hiện. 7 getPrefi) Phương thức này trả tiền tố của các yếu tố hiện tại. 8 getName() Phương pháp này trả về tên của thẻ. 9 gettext() Phương pháp này trả về văn bản cho rằng yếu tố cụ thể. 10 isWhitespace() Phương pháp này kiểm tra xem các sự kiện TEXT hiện chứa các ký tự không gian chỉ có màu trắng. Ví dụ Dưới đây là một ví dụ minh hoạ việc sử dụng lớp XmlPullParser . Nó tạo ra một ứng dụng phân tích cú pháp cơ bản cho phép bạn phân tích một tài liệu hiện RSS và sau đó hiển thị kết quả. Để thử nghiệm với ví dụ này, bạn có thể chạy trên một thiết bị thực tế hoặc trong một mô phỏng. Các bước Mô tả 1 Bạn sẽ sử dụng Android studio để tạo ra một ứng dụng Android dưới một gói com.example.sairamkrishna.myapplication. Trong khi tạo dự án này, chắc chắn bạn Target SDK và biên dịch với các phiên bản mới nhất của Android SDK sử dụng các cấp cao hơn của các API. 2 Sửa file src/ MainActivity.java để thêm mã cần thiết. 3 Sửa đổi res/layout/activity_main để thêm các thành phần XML tương ứng. 4 Tạo một file java mới theo src/HandleXML.java để lấy và phân tích dữ liệu XML. 5 Tạo một file java mới theo src/second.java để hiển thị kết quả của XML 6 Sửa AndroidManifest.xml để thêm sự cho phép internet cần thiết. 7 Chạy ứng dụng và chọn một thiết bị Android chạy và cài đặt các ứng dụng trên nó và kiểm tra kết quả. Sau đây là nội dung của các sửa đổi tập tin chính hoạt động src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.util.Set; public class MainActivity extends Activity { EditText title,link,description; Button b1,b2; private String finalUrl="http://tutorialspoint.com/android/sampleXML.xml"; private HandleXML obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); title = (EditText) findViewById(R.id.editText); link = (EditText) findViewById(R.id.editText2); description = (EditText) findViewById(R.id.editText3); b1=(Button)findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { obj = new HandleXML(finalUrl); obj.fetchXML(); while(obj.parsingComplete); title.setText(obj.getTitle()); link.setText(obj.getLink()); description.setText(obj.getDescription()); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in=new Intent(MainActivity.this,second.class); startActivity(in); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } >> Khóa học lập trình android tại hà nội ! Nôi dung file src/HandleXML.java. package com.example.rssreader; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.util.Log; public class HandleXML { private String title = "title"; private String link = "link"; private String description = "description"; private String urlString = null; private XmlPullParserFactory xmlFactoryObject; public volatile boolean parsingComplete = true; public HandleXML(String url){ this.urlString = url; } public String getTitle(){ return title; } public String getLink(){ return link; } public String getDescription(){ return description; } public void parseXMLAndStoreIt(XmlPullParser myParser) { int event; String text=null; try { event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = myParser.getText(); break; case XmlPullParser.END_TAG: if(name.equals("title")){ title = text; } else if(name.equals("link")){ link = text; } else if(name.equals("description")){ description = text; } else{ } break; } event = myParser.next(); } parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchXML(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); InputStream stream = conn.getInputStream(); xmlFactoryObject = XmlPullParserFactory.newInstance(); XmlPullParser myparser = xmlFactoryObject.newPullParser(); myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); myparser.setInput(stream, null); parseXMLAndStoreIt(myparser); stream.close(); } catch (Exception e) { } } }); thread.start(); } } Tạo một file với tên second.java trong thư mục java/second.java package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; /** * Created by Sairamkrishna on 4/6/2015. */ public class second extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); WebView w1=(WebView)findViewById(R.id.webView); w1.loadUrl("http://tutorialspoint.com/android/sampleXML.xml"); } } Tạo một file xml tại res/layout/second_main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" androidrientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <WebView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/webView" android:layout_gravity="center_horizontal" /> </LinearLayout> Nội dung res/layout/activity_main.xml − <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" androidaddingLeft="@dimen/activity_horizontal_margin" androidaddingRight="@dimen/activity_horizontal_margin" androidaddingTop="@dimen/activity_vertical_margin" androidaddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:transitionGroup="true"> <TextView android:text="RSS example" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textview" android:textSize="35dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Tutorials point" android:id="@+id/textView" android:layout_below="@+id/textview" android:layout_centerHorizontal="true" android:textColor="#ff7aff24" android:textSize="35dp" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/imageView" androidrc="@drawable/abc" android:layout_below="@+id/textView" android:layout_centerHorizontal="true" android:theme="@style/Base.TextAppearance.AppCompat" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_below="@+id/imageView" android:hint="Tittle" android:textColorHint="#ff69ff0e" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText2" android:layout_below="@+id/editText" android:layout_alignLeft="@+id/editText" android:layout_alignStart="@+id/editText" android:textColorHint="#ff21ff11" android:hint="Link" android:layout_alignRight="@+id/editText" android:layout_alignEnd="@+id/editText" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText3" android:layout_below="@+id/editText2" android:layout_alignLeft="@+id/editText2" android:layout_alignStart="@+id/editText2" android:hint="Description" android:textColorHint="#ff33ff20" android:layout_alignRight="@+id/editText2" android:layout_alignEnd="@+id/editText2" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Fetch" android:id="@+id/button" android:layout_below="@+id/editText3" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_toLeftOf="@+id/imageView" android:layout_toStartOf="@+id/imageView" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Result" android:id="@+id/button2" android:layout_alignTop="@+id/button" android:layout_alignRight="@+id/editText3" android:layout_alignEnd="@+id/editText3" /> </RelativeLayout> Nội dung file res/values/string.xml <resources> <string name="app_name">My Application</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> </resources> Nội dung file mặc định AndroidManifest.xml. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sairamkrishna.myapplication" > <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".second"></activity> </application> </manifest> Kết quả:Ấn nút Fetch Feed để lấy dữ liệu RSS. Sau khi ấn, màn hình sẽ hiện thị dữ liệu RSS.Chỉ ấn nút kể quả để nhìn XML, Trung tâm đào tạo hoc photoshop căn bản với đội ngũ giáo viên trẻ, nhiệt tình và học php cơ bản nâng cao tại VietPro!