Beginner Android, use custom XML resources (18)

Hits: 0

Similarly, like animation resources, [XML] resources are not created by default, and you need to manually create res/xml by yourself

The following first defines an xml file, and then parses it

Create books.xml in res/xml

<?xml version="1.0" encoding="utf-8"?> 
< books > 
    < book  price = "99.0" publication date = "2008" > Java </ book > 
    < book  price = "89.0" publication date = "2009" > Jave EE </ book > 
    < book  price = "69.0" publication date = "2009" > Ajax </ book > 
</ books >

Let’s put a button in the main interface, parse the XML when clicked, and then display it in the text box below

package WangLi.Resouce.XmlResTest;
import org.xmlpull.v1.XmlPullParserException;

import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class XmlResTest extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        Button bn = (Button)findViewById(;
        bn.setOnClickListener( new OnClickListener (){
             public  void  onClick (View arg0)
                 //Get the parser that parses the resource according to the ID of the XML resource 
                //XmlResourceParser is a subclass of XmlPullParser
                XmlResourceParser xrp = getResources().getXml(R.xml.books);
                    StringBuilder sb = new StringBuilder( "" );
                     //Not yet at the end of the XML document 
                    while (xrp.getEventType()!=XmlResourceParser.END_DOCUMENT)
                        //If the start tag is encountered 
                        if (xrp.getEventType()==XmlResourceParser.START_TAG)
                            //Get the tag name of the tag
                            String tagName = xrp.getName();
                                //Get the attribute value according to the attribute name 
                                String bookName = xrp.getAttributeValue( null , "price" );
                                sb.append( "Price:" );
                                //Get the attribute value according to the attribute index 
                                String bookPrice = xrp.getAttributeName( 1 );
                                sb.append( "Published Date:" );
                                sb.append( "Book Title:" );
                                 //Get the value of the text node
                        // Get the next event of the parser
                    EditText show = (EditText)findViewById(;
                catch(XmlPullParserException e)
                catch(IOException e)

The effect is as follows, when the button is clicked, the parsed XML file content appears in the text box

You may also like...

Leave a Reply

Your email address will not be published.