1.效果图:点击解析,显示books的信息
2.xml:boos.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <books> 3 <book price="100" pubDate="2018">Java</book> 4 <book price="90" pubDate="2017">Xml</book> 5 <book price="80" pubDate="2016">Android</book> 6 </books>
3.activity_main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.example.app3.MainActivity" 11 android:orientation="vertical"> 12 13 14 <Button 15 android:id="@+id/bt" 16 android:hint="解析" 17 android:layout_width="match_parent" 18 android:layout_height="wrap_content" /> 19 <TextView 20 android:id="@+id/tv" 21 android:layout_width="wrap_content" 22 android:layout_height="wrap_content"/> 23 </LinearLayout>
4.MainActivity.java
1 package com.example.app3; 2 3 import android.content.res.XmlResourceParser; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 import android.widget.TextView; 9 10 import org.xml.sax.helpers.XMLReaderAdapter; 11 import org.xmlpull.v1.XmlPullParserException; 12 13 import java.io.IOException; 14 15 public class MainActivity extends AppCompatActivity { 16 private Button button; 17 private TextView textView; 18 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 button = (Button) findViewById(R.id.bt); 24 textView = (TextView) findViewById(R.id.tv); 25 button.setOnClickListener(new View.OnClickListener() { 26 @Override 27 public void onClick(View v) { 28 XmlResourceParser xrp = getResources().getXml(R.xml.books); 29 30 try { 31 StringBuffer stringBuffer = new StringBuffer(); 32 while (xrp.getEventType()!=XmlResourceParser.END_DOCUMENT){ 33 if(xrp.getEventType() == XmlResourceParser.START_TAG){ 34 //获取标签名 35 String bookinfo = xrp.getName(); 36 if(bookinfo.equals("book")){ 37 String bookprice = xrp.getAttributeValue(0); 38 stringBuffer.append("价格:"); 39 stringBuffer.append(bookprice+" "); 40 41 String bookDate = xrp.getAttributeValue(null,"pubDate"); 42 stringBuffer.append("出版日期:"); 43 stringBuffer.append(bookDate+" "); 44 45 46 String bookname = xrp.nextText(); 47 stringBuffer.append("作者:"); 48 stringBuffer.append(bookname); 49 50 } 51 stringBuffer.append(" "); 52 } 53 xrp.next(); 54 } 55 textView.setText(stringBuffer.toString()); 56 57 } catch (XmlPullParserException e) { 58 e.printStackTrace(); 59 }catch (IOException e) { 60 e.printStackTrace(); 61 } 62 } 63 }); 64 } 65 }