Creating and parsing XML tutorials on the Android 3.0 platform

Source: Internet
Author: User
Tags gettext object model



To use the examples given in this article, you need to install and configure the following software. See resources for RELATED links.



Common abbreviations adt:android Development tools,android Development tools
Api:application programming interface, application programming interface
Avd:android Virtual Device,android Device
Dom:document object model, document objects
ide:integrated Development Environment, integrated development environment
Json:javascript Object Notation,javascript Objects notation
Sax:simple API for Xml,xml Simple API
Sdk:software Development Kit, Software Development Kit
Ui:user Interface, user interface
Xml:extensible Markup Language, Extensible Markup Language
Install the Eclipse IDE.
Installs the Android Development Tools (ADT) plug-in for Eclipse, which provides a set of extensions for developing an Android application in Eclipse.
Download and install the Android SDK Platform, which provides tools for developing Android applications.
Choose Windows > Android SDK and AVD Manager to launch the Android SDK and AVD Manager in Eclipse.
Create an Android Virtual Device (AVD) in the Android SDK and AVD Manager, which is an Android emulator.
Please select Platform 3.0 and API 11 for AVD.



Create an XML document



In this section, you will create an XML document on Android. The first step is to create an Android project.



Select File > New in the Eclipse IDE. In the New dialog box, choose Android > Android Project. then click Next.
In the New Android Project window, as shown in Figure 1, specify:
Project Name: Creatingxml
Build target check box: Android Platform 3.0 and API 11
Property:
Application Name: Creatingxml
Package Name: Android.xml
Select Create activity: Activity Class (Creatingxml). An activity represents a user interaction at a time. This class extends the activity class and creates a window for the UI.
Minimum SDK version: 11



Figure 1. Create an Android project for Platform 3.0


    1. Click Next.




    1. Click Finish. This creates an Android project for creating an XML document. The Android project contains the following files:
    2. An active classCreatingXMLthat extends the activity class.
    • Res/layout/main.xml file that specifies the layout of the Android UI component.
    • Androidmanifest.xml file that contains the application configuration, such as the package name, the primary activity, application components, processes, and lowest API levels that are initiated when the Android application is launched.



  • Figure 2 shows the directory structure of the Android project Creatingxml.



    Figure 2. Android Project for creating XML documents


    In the Res/layout/main.xml file, specify the layout of the Android UI component. Create one andLinearLayoutset itandroid:orientationtovertical. In this example, you will display the XML document in the form of a text message. Add an element with an ID toxmlresultTextViewdisplay the XML document, as shown in Listing 1.



    Listing 1. layout file 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>



    In the Androidmanifest.xml file, specifyActivityrunCreatingXML. Useuses-sdkelement 11 to specify the lowest version of Android. Use the active element to specify the activity and the child elementintent-filteraction. Listing 2 shows the file.



    Listing 2. configuration file 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= "/>
    
        <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> 




    You will nowCreatingXMLcreate an XML document in the active class that extends the classActivity. Because the example usesjavax.xml.parsers.DocumentBuilderto create an XML document, you need to import the following.
      • javax.xml.parsers.DocumentBuilderClass
      • javax.xml.parsers.DocumentBuilderFactoryClass
      • org.w3c.domPackage
      • javax.xml.transform.TransformerFactoryClass
      • javax.xml.transform.TransformerClass
      • javax.xml.transform.dom.DOMSourceClass
      • javax.xml.transform.stream.StreamResultClass
    The method is called when the activity is startedonCreate(Bundle savedInstanceState). In aonCreatemethod, you can use thesetContentViewmethod to set the UI and use thesetContentView(R.layout.main);set layout resource.
    Use methods in the Main.xml file tofindViewByIddefine the Android widgetTextViewobject (its IDxmlresult) as follows:TextView xmlResult = (TextView) findViewById(R.id.xmlresult);.
    newInstance()createsDocumentBuilderFactoryan instance of an object using a static method. UseDocumentBuilderFactorythe method of the classnewDocumentBuilder()to create anDocumentBuilderobject, as shown in Listing 3.



    Listing 3. Create a Documentbuilder


     Documentbuilderfactory documentbuilderfactory = Documentbuilderfactory.newinstance ();
    Documentbuilder Documentbuilder = Documentbuilderfactory.newdocumentbuilder (); 




    An XML document is represented by a DOM structure.DocumentBuildernewDocument()Create a new object using the method of the classDocument:Document document = documentBuilder.newDocument();.
    UsecreateElement()methods to create the root element of a Document object"catalog":Element rootElement = document.createElement("catalog");.
    As shown in Listing 4, you can usesetAttributemethods to set the and properties on the root elementpublisherjournal.



    Listing 4. Set root element properties


     Rootelement.setattribute ("journal", "Oracle Magazine");
    Rootelement.setattribute ("publisher", "Oracle Publishing"); 




    UseappendChild()the method to attach the root element to anDocumentobject:document.appendChild(rootElement);.
    Use thecreateElement()method to create an"article"element. UseappendChild()the method to attach the element to the root element, as shown in Listing 5.



    Listing 5. Create a "article" element


     Element articleelement = document.createelement ("article");
    Rootelement.appendchild (articleelement); 




    Add an element to the element, as shown in Listing 6"article""edition".



    listing 6. Add "edition" element


     Element editionelement = document.createelement ("edition");
    Articleelement.appendchild (editionelement); 




    UsecreateTextNode()the method to"edition"add a text node to the element. Set the value of the text node to "SEPT-OCT 2005" as follows:editionElement.appendChild(document.createTextNode("Sept-Oct 2005"));.
    Similarly, create an"title"element and add it to the"article"element. Add a text node to the element, as shown in Listing 7,"title"and set its value to"Creating Search Pages".



    Listing 7. Create a text node


     Element titleelement = document.createelement ("title");
    Articleelement.appendchild (titleelement);
    Titleelement.appendchild (document.createTextNode ("Creating Search Pages")); 




    "article"adds an element to an element"author"."author"Add a text node to the element and set its value to"Steve Muench", as shown in Listing 8.



    Listing 8. Add "Author" element


     Authorelement = document.createelement ("author");
    Articleelement.appendchild (authorelement);
    Authorelement.appendchild (document.createTextNode ("Steve muench")); 




    Adds another element to the root element"article". You can create the XML document DOM structure in the same way as non-Android applications. This example performs the following actions:
      • Documentto output a DOM object to aByteArrayOutputStream
      • Gets the XML document as a stringOutputStream
      • Set upTextViewa string on a widget on Android
    newInstance()creates an object using a static methodTransformerFactory. As shown in Listing 9,factoryan object is created using the object'snewTransformer()methodTransformer.



    Listing 9. Create a Transformer object


     Transformerfactory factory = Transformerfactory.newinstance ();			
    Transformer Transformer = Factory.newtransformer (); 




    Create anjava.util.Propertiesobject and set the following output properties:
      • Indent (INDENT)
      • Output Format (METHOD)
      • XML Declaration (OMIT_XML_DECLARATION)
      • XML version (VERSION)
      • How XML documents are encoded (ENCODING)
    To convert the DOM structure, you need to useSourceobjects and objectsResult.Documentcreates an object from an objectDOMSource. To get the output, we'llByteArrayOutputStreamcreate anByteArrayOutputStreamobject and anStreamResultobject, as shown in Listing 10.



    listing 10. Transforming the DOM structure


     Domsource Domsource = new Domsource (Document.getdocumentelement ());
    OutputStream output = new Bytearrayoutputstream ();
    Streamresult result = new Streamresult (output); 




    UseTransformerthe method of the objecttransform()Documentto transform the object, as follows:transformer.transform(domSource, result);.
    Gets the object from theByteArrayOutputStreamobjectStringand setsTextViewxmlResultthe on the widgetString.



    listing 11. Get and set string


     String xmlstring = output.tostring ();
    Xmlresult.settext (xmlstring); 




    Listing 12 shows theActivityclassCreatingXML.



    Listing 12. Activity classCreatingXML



    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) {
            }
    
        }
    }


    Now you can run the Android application. Right-click the Creatingxml application node and select Run as > Android application, as shown in Figure 3.



    Figure 3. Running the Android application


    The Android AVD is launched, and the Android application is deployed on AVD, as shown in Figure 4.



    Figure 4. Applications installed on the Android device


    Click the Creatingxml application icon. Start the application activity and create and display an XML document on the Android device, as shown in Figure 5.



    Figure 5. Create and display an XML document on an Android device


    Back to the top of the page
    Parsing XML Documents
    This section describes how to parse XML documents. You can use a standard DOM with a SAX parser or other parser. In the example of using Org.xmlpull.v1.XmlPullParser, the XML document Catalog.xml will be parsed, as shown in Listing 13.



    List 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> 




    As with the previous section, creating an XML document, you need to create an Android project to parse the XML document.
    1. Select File > New in the Eclipse IDE. In the New dialog box, choose Android > Android Project. then click Next.
    2. In the New Android Project window, as specified in Figure 6:
      • Project Name:ParsingXML
      • Build target check box: Android Platform 3.0 with API 11.
      • Property:
        • Application Name:ParsingXML
        • Package Name:android.xml
        • Select "Create activity": Activities Class (ParsingXML)
        • Minimum SDK version: 11


      Figure 6. Create an Android project to parse an XML document


    3. Click Finish.
      This creates an Android project that contains the following:
      • AActivityclassParsingXML
      • A res/layout/main.xml layout file
      • An androidmanifest.xml application configuration file
    Parses the XML document and outputs the element value using the label, outputting the label to the widget with the element text node valueTextView.
    1. In the Main.xml file, add a widget for each label and element text node valueTextView.
    2. Create oneLinearLayoutandandroid:orientationset to"vertical".
    3. to add aTextViewelement with the following ID:
      • journal_label li>
      • "journal"
      • "Publisher_label"
      • li> publisher
      • "Edition1_label"
      • strong>"Edition1"
      • "Title1_label"
      • code> "Title1"
      • "Author1_label"
      • Author1 "
      • " Edition2_label "
      • " title2_ Label "
      • " Title2 "
      • " Author2_label "
      • "Author2"
    Listing 14 shows the Main.xml file.



    listing 14. layout File 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>




    Specify the following in the Androidmanifest.xml file:
      • To runactivity, specified asParsingXML
      • Useuses-sdkelements to specify the lowest version of Android as 11
      • Use the active element with the child element designationactivity,intent-filterandaction
    Listing 15 shows the Androidmanifest.xml file that was last obtained:



    listing 15. configuration file 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= "/>
    
        <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> 




    To parse an XML document source, the example uses Android.content.res.XmlResourceParser, which extends the Xmlpullparser interface. You need to create a directory for the XML document in the Res directory.
      1. Create a directory named XML in the Res directory, and then copy the XML document into the Res/xml directory.
      2. In theParsingXMLactive class, import the Android.content.res.XmlResourceParser and Org.xmlpull.v1.XmlPullParser interfaces.
        The method was called when the activity was startedonCreate(Bundle savedInstanceState).
      3. In aonCreatemethod, you usesetContentViewmethod and layout resources to set the UI, such as:setContentView(R.layout.main);
      4. Use thefindViewByIdmethod and widget ID to get the Android widget defined in the Main.xml fileTextView, as shown in Listing 16.



    listing 16. Get TextView Widget


     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); 




    Create an object from the Catalog.xml document in the Res/xml directoryXmlResourceParser, the code is as follows:XmlResourceParser xpp = getResources().getXml(R.xml.catalog);.
    You will useXmlResourceParserto parse the XML document, which is also a pull parser (extending the Xmlpullparser interface). The pull parser handles the XML document as a series of parsing events. You can usenext()the method to get the next resolution event, as follows:xpp.next();.
    UsegetEventTypeintthe method to get the event type, which returns aint 值:eventType = xpp.getEventType();.
    All possible values are shown in Table 1int.



    table 1. Event Typeintvalues


    int Value Description
    COMMENT A section of XML annotations
    Docdecl XML Document Type description
    End_document End of document
    End_tag The end of an element label
    Ignorable_whitespace Spaces that can be ignored
    Processing_instruction Processing instructions
    Start_document Document Start
    Start_tag The beginning of an element label
    TEXT Character data




    XML documents only need to parse elements and element text nodes. These properties do not generate events, and you can retrieve them from the element. You will only seeSTART_TAGtheTEXTevent type, which corresponds to the element start tag and the element text node, respectively. You first determine the element label and then get the text node value of the element label. Useintvariablesiterto represent different elements in an XML document"article", and useStringvariableselemtextto define the element label names. To specify a variable for the iteratorintand specify a variable for the element nameString, use the code in Listing 17.



    listing 17. Specify variable


     int iter = 0;
    String elemtext = null; 




    Before the end of the XML document is reached:
      • Determine event Type
      • Get element label name and element label text value
      • SetTextViewthe text node value on the corresponding widget
    For example, get the element label name as in Listing 18.



    listing 18. The name of the element that gets the start tag


     while (EventType!= xmlpullparser.end_document) {
                  if (EventType = = Xmlpullparser.start_tag) {
             String elemname = Xpp.getname ();
    ...
    ...
                                                             }
                                                     } 




    If the element label name is"catalog", get"journal""publisher"the property value with and set the"journal""publisher"property value on the TextView widget. You can useXmlResourceParserthegetAttributeValue()method to get the property value, as shown in Listing 19.



    listing 19. Getting and setting property values


     if (elemname.equals ("Catalog")) {			
    String journalattr = Xpp.getattributevalue (NULL, "Journal");
    String publisherattr = Xpp.getattributevalue (null, publisher);
    Journal.settext (journalattr);				
    Publisher.settext (publisherattr);	
    ...
    } 




    Increase the"article"value of the iterator variable for each elementiter, as shown in Listing 20.



    listing 20. Increasing the value of a variable


     if (Elemname.equals ("article")) {
         iter = iter + 1;
                                     } 




    If the event type isTEXTthe text node value is obtained, and theTextViewtext node value is set on the appropriate widget. You can useelemtextStringvariables to get the element label name, which is set for the event typeSTART_TAG. UseXmlResourceParserthegetText()method to get the text node value. Use thesetTextmethodTextViewto set the text node value on the widget, as shown in Listing 21.



    listing 21. Get the text node value


     else if (EventType = = Xmlpullparser.text) {
    //obtain the element name and element TEXT node values and 
    //set the T EXT node values on the corresponding TextView 
    //widgets
    } 




    Listing 22 shows theActivityclassParsingXML.



    listing 22. Activity Class 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) {
             }
    
        }
    }




    To run the Android application, right-click the Parsingxml application and select Run as > Android application, as shown in Figure 7.



    Figure 7. Running an Android application to parse an XML document


    The Android AVD is started and the Parsingxml application is already installed on the Android device, as shown in Figure 8.



    Figure 8. Parsingxml applications installed on Android devices


    Click the Parsingxml application to start the application activity. Then parse the XML document Catalog.xml and output it to the Android device, as shown in Figure 9.



    Figure 9. XML document node values obtained through resolution


    The element label is stacked vertically with the element text node. The layout of the text node value on the right side of the corresponding label is preferable. In order to implement a custom layout where the text node value is on the right side of the label, you can useRelativeLayoutinsteadLinearLayout.TextViewYou can use the widget'sandroid:layout_marginLeftproperties to have the text node value appear on the right side of the label.android:layout_belowYou can use attributes to make text node values appear below the values of the text nodes in the previous line.
    RelativeLayoutOther properties are provided, for exampleandroid:layout_toRightOf, for outputting a widget to the right of another widget, andandroid:layout_toLeftOffor outputting a component to the left of another component. Listing 23 shows the relative layout of the main.xml.



    listing 23. Relative layout



    <?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>




    Returns the Parsingxml application after modifying the layout. The XML document resolves and outputs node values in the specified layout, as shown in Figure 10.



    Figure 10. Formatted XML document node value


    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.