Android Chapter18A Reading XML Data

  • Upload
    letuyen

  • View
    38

  • Download
    0

Embed Size (px)

Citation preview

  • Android Reading XML Data

    Using SAX and W3C Parsers

    18A

    Victor Matos Cleveland State University

    Notes are based on:

    Android Developers http://developer.android.com/index.html XML Data http://www.w3.org http://www.saxproject.org/

  • 2

    18. Android Reading XML Files

    XML Data

    2

    What is XML?

    Extensible Markup Language (XML) is a set of rules for encoding documents in a readable form.

    Similar to HTML but are user-defined. It is defined in the XML Specification produced by the W3C.

    XML's design goals emphasize transparency, simplicity, and

    transportability over the Internet.

    Example of XML-based languages include: RSS , Atom, SOAP, and XHTML.

    Several office productivity tools default to XML format for internal data storage. Example: Microsoft Office, OpenOffice.org, and Apple's iWork.

  • 3

    18. Android Reading XML Files

    XML Data

    3

    How is XML used? 1. XML is used for defining and documenting object classes.

    2. For example, an XML document (.xml) might contain a

    collection of complex employee elements, such as ... which lexically includes an id and title attributes.

    3. Employee may also hold other inner elements such as name, country, city, and zip.

    4. An XML-Data schema (.xsd) can describe such syntax.

    XML Data http://www.w3.org

  • 4

    18. Android Reading XML Files

    XML Data

    4

    How is XML used? Employee Example

    Microsoft XML Notepad

  • 5

    18. Android Reading XML Files

    XML Data

    5

    Example 1. Employee.xml

    Example taken from: Microsoft XmlNotepad 2007 http://www.microsoft.com/downloads/en/details.aspx?familyid=72d6aa49787d4118ba5f4f30fe913628&displaylang=en

    Nancy J. Davolio

    507 20th Ave. E. Apt. 2A Seattle 98122 U.S.A. 5/7682 (206) 5559857 Photo.jpg

    . . .

    Element: Street

    Attributes: id, title

  • The registered IANA country code of the format xxxx. For example: enus. The ITG assigned 5 digit employee identification 6

    18. Android Reading XML Files

    XML Data

    6

    Example 1. Employee.xsd Schema Definition (fragment)

    Only a fragment. Lines removed

  • 7

    18. Android Reading XML Files

    XML Data

    7

    Example 2. Mapping with KML (fragment) KML is a file format used to display geographic data in an Earth browser such as Google Earth, Google Maps, and Google Maps for mobile

    Reference: http://code.google.com/apis/kml/documentation/kml_tut.html

  • 8

    18. Android Reading XML Files

    XML Data

    8

    Example 2. Mapping with KML (View from Google Earth)

    Reference: http://code.google.com/apis/kml/documentation/kml_tut.html

  • 9

    18. Android Reading XML Files

    XML Data

    9

    Example 2. Mapping with KML & Playing Golf

    Club Men Women Driver 200-230-260 150-175-200 3-wood 180-215-235 125-150-180 2-Hybrid 170-195-210 105-135-170 3-Hybrid 160-180-200 100-125-160 4-iron 150-170-185 90-120-150 5-iron 140-160-170 80-110-140 6-iron 130-150-160 70-100-130 7-iron 120-140-150 65-90-120 8-iron 110-130-140 60-80-110 9-iron 95-115-130 55-70-95 PW 80-105-120 50-60-80 SW 60-80-100 40-50-60

    Typical Distances for (Good) Amateur Players

    Reference: Cartoon by Lash Leroux available at http://www.golfun.net/lash3.htm

  • 10 10

    18. Android Reading XML Files

    XML Data

    10

    Example 2. Mapping with KML (fragment)

  • 11

    18. Android Reading XML Files

    XML Data

    11

    Example 2. Reading/Parsing a Resource KML File (code) In this example we will read an XML file saved in the /re/xml folder.

    The example file contains a set of place-markers around a golf course.

    A SAX (Simple API for XML) XmlPullParser is used to scan the document using the .next() method and detect the main eventTypes

    START_TAG TEXT END_TAG END_DOCUMENT

    When the beginning of a tag is recognized, we use the .getName()

    method to grab the tag name.

    We use the method .getText() to extract data after TEXT event.

    SAX Simple API for XML

    Reference: http://www.saxproject.org/

  • 12

    18. Android Reading XML Files

    XML Data

    12

    Example 2. Reading/Parsing a Resource KML File (code) Attributes from an element can be extracted using the methods:

    .getAttributeCount() .getAttributeName() .getAttributeValue()

    For the example below:

    Tee Hole 1

    SAX Simple API for XML

    Reference: http://www.saxproject.org/

    Element: name Text: Tee Hole 1

    Attributes AttributeName AttributeValue

    par 4

    yards 390

  • 13

    18. Android Reading XML Files

    XML Data

    13

    Example 2. Reading/Parsing a Resource KML File

    Using the XmlPullParser class to generate scanner/parser to traverse an XML document

    SAX Simple API for XML

  • SAX Simple API for XML

    14

    18. Android Reading XML Files

    XML Data

    14

    Example 2. Reading a Resource KML File (code)

  • SAX Simple API for XML

    15

    18. Android Reading XML Files

    XML Data

    15

    Example 2. Reading a Resource KML File (code) // demonstrates the reading of XML resource files. In this case // containing mapping data (kml) holding inner elements as well // as common text tags. // --------------------------------------------------------------------- package ucr.xmlreading; import . . . public class Main extends Activity {

    private TextView txtMsg; Button btnGoParser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView) findViewById(R.id.txtMsg); btnGoParser = (Button)findViewById(R.id.btnReadXml); btnGoParser.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

    btnGoParser.setEnabled(false); XmlPullParser parser = getResources().getXml(R.xml.manakiki_hole1_v2); StringBuilder stringBuilder = new StringBuilder(); String nodeText = ""; String nodeName = ";

  • 16

    18. Android Reading XML Files

    XML Data

    16

    Example 2. Reading a Resource KML File (code) try {

    int eventType = -1; while (eventType != XmlPullParser.END_DOCUMENT) { eventType = parser.next(); if(eventType == XmlPullParser.START_DOCUMENT) { stringBuilder.append("Start document \n"); } else if(eventType == XmlPullParser.END_DOCUMENT) { stringBuilder.append("End document \n"); } else if(eventType == XmlPullParser.START_TAG) { nodeName = parser.getName(); stringBuilder.append("Start tag:\t" + parser.getName() + "\n"); innerAttributes(parser, stringBuilder); } else if(eventType == XmlPullParser.END_TAG) { stringBuilder.append("End tag: \t" + parser.getName() + "\n"); } else if(eventType == XmlPullParser.TEXT) {

    if (nodeName.equals("name")) stringBuilder.append("\n"); nodeText = parser.getText(); stringBuilder.append("Text: \t\t" + parser.getText() + "\n"); tokenizeText(parser, stringBuilder, nodeName);

    } txtMsg.setText(stringBuilder.toString());

    } }catch(Exception e) { Log.e("", e.getMessage()); }

    } }); }//onCreate

    SAX Simple API for XML

  • 17

    18. Android Reading XML Files

    XML Data

    17

    Example 2. Reading a Resource KML File (code) private void innerAttributes(XmlPullParser parser, StringBuilder stringBuilder) { // trying to detect inner elements nested around gcData tag

    String name = parser.getName(); if (!name.equals("gcPlace")) return; String gcName = null; String gcCity = null; String gcState= null; // Processing a fragment of the type: // if((name != null) && name.equals("gcPlace")) {

    int size = parser.getAttributeCount(); for(int i = 0; i < size; i++) {

    String attrName = parser.getAttributeName(i); String attrValue = parser.getAttributeValue(i); if((attrName != null) && attrName.equals("gcName")) { gcName = attrValue; } else if ((attrName != null) && attrName.equals("gcCity")) { gcCity = attrValue; } else if ((attrName != null) && attrName.equals("gcState")) { gcState = attrValue; }

    } if((gcName != null) && (gcCity != null) && (gcState != null) ) {

    stringBuilder.append(" \t:" + gcName + ", " + gcCity + ", " + gcState + "\n"); txtMsg.setText(" \t:" + stringBuilder.toString() + "\n");

    } }

    }//innerElements

    SAX Simple API for XML

  • 18

    18. Android Reading XML Files

    XML Data

    18

    Example 2. Reading a Resource KML File (code) private void tokenizeText(XmlPullParser parser, StringBuilder stringBuilder, String nodeName){

    // interpreting text enclosed in a coordinates tag String text = parser.getText(); if ((text==null) || (!nodeName.equals("coordinates"))) return; // parsing latitude, longitude, altitude String [] loc = text.split(","); text = " " + nodeName + " Lon: " + loc[0] + " Lat: " + loc[1] + "\n"; stringBuilder.append(text); txtMsg.setText(stringBuilder );

    }//tokenizeBuilder }//Main

    SAX Simple API for XML

  • 19

    18. Android Reading XML Files

    XML Data

    19

    Example 3. Reading XML from the SD card (code) In this example we read the same XML data of the previous example; however the file is stored in the SD card. Rather than stepping through the SAX eventTypes recognized by an XmlPullParser, a W3C DocumentBuilder parser will be used here. The XML file is given to the W3C parser to construct an equivalent tree. Elements from the XML file are represented in the parse-tree as NodeLists. These ArrayList-like collections are made with the .getElementsByTagName() method. An individual node from a NodeList could be explored using the methods: .item(i), .getName() , .getValue() , .getFirstChild() , .getAttributes(),

    Note: The World Wide Web Consortium (W3C.org) is an international community that develops open standards to ensure the long-term growth of the Web.

  • 20

    18. Android Reading XML Files

    XML Data

    20

    Example 3. Reading an XML file from the SD card (code)

  • 21

    18. Android Reading XML Files

    XML Data

    21

    Example 3. Reading an XML file from the SD card (code)

  • package csu.matos; import . . . public class ReadingXMLVersion1Activity extends Activity { Button btnGo; EditText txtMsg; XmlPullParser parser; String elementName; String attributeName; String attributeValue; StringBuilder str; @Override public void onConfigurationChanged(Configuration newConfig) { // needed to avoid re-starting app on orientation changes super.onConfigurationChanged(newConfig); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (EditText) findViewById(R.id.editText1); 22

    18. Android Reading XML Files

    XML Data

    22

    Example 3. Reading an XML file from the SD card (code)

    NOTE: You need to modify the Manifest to stop reorientation. Add the following attributes to the element android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation"

  • btnGo = (Button) findViewById(R.id.button1); btnGo.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { txtMsg.setTextSize(10); useW3cOrgDocumentBuilder(); // see www.w3c.org } }); }// onCreate private void useW3cOrgDocumentBuilder() { try { String kmlFile = Environment.getExternalStorageDirectory() .getPath() + "/manakiki_hole2_v2.kml"; InputStream is = new FileInputStream(kmlFile); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document document = docBuilder.parse(is); NodeList listNameTag = null; NodeList listCoordinateTag = null; if (document == null) { txtMsg.setText("Big problems with the parser"); return; } 23

    18. Android Reading XML Files

    XML Data

    23

    Example 3. Reading an XML file from the SD card (code)

  • 24

    18. Android Reading XML Files

    XML Data

    24

    Example 3. Reading an XML file from the SD card (code) StringBuilder str = new StringBuilder(); // dealing with 'name' tagged elements listNameTag = document.getElementsByTagName("name"); // showing 'name' tags for (int i = 0; i < listNameTag.getLength(); i++) { Node node = listNameTag.item(i); int size = node.getAttributes().getLength(); String text = node.getTextContent(); str.append("\n " + i + ":- name text > " + text); // get all attributes of the current name element (i-th hole) for (int j = 0; j < size; j++) { String attrName = node.getAttributes().item(j).getNodeName(); String attrValue = node.getAttributes().item(j).getNodeValue(); str.append("\n\t attr. info-" + i + "-" + j + ": " + attrName + " " + attrValue); } }

  • 25

    18. Android Reading XML Files

    XML Data

    25

    Example 3. Reading an XML file from the SD card (code) // dealing with 'coordinates' tagged elements listCoordinateTag = document.getElementsByTagName("coordinates"); // showing 'coordinates' tags for (int i = 0; i < listCoordinateTag.getLength(); i++) { String coordText = listCoordinateTag.item(i).getFirstChild() .getNodeValue(); str.append("\n\t " + i + ": " + coordText); } txtMsg.setText(str.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }// useW3cOrgDocumentBuilder }// Activity

  • 26

    18. Android Reading XML Files

    XML Data

    26

    Example 3. Reading an XML file from the SD card (code) private int distanceYards(GolfMarker gm){

    // calculating distance (yards) between two coordinates int intDistance = 0; double distance = 0; Location locationA = new Location("point: Here"); locationA.setLatitude(Double.parseDouble(aLatitude)); locationA.setLongitude(Double.parseDouble(aLongitude)); Location locationB = new Location("point: F/M/B Green"); locationB.setLatitude(Double.parseDouble(bLatitude)); locationB.setLongitude(Double.parseDouble(bLongitude)); distance = locationA.distanceTo(locationB) * METER_TO_YARDS; intDistance = (int) Math.round(distance); return intDistance;

    }

    }// GolfMarker

    NOTE: calculating distance between two locations. Not implemented yet

  • 27 27

    18. Android Reading XML Files

    Reading XML Files

    27

    < Questions />

    SAX Simple API for XML

    Android Reading XML Data Using SAX and W3C ParsersSlide Number 2Slide Number 3Slide Number 4Slide Number 5Slide Number 6Slide Number 7Slide Number 8Slide Number 9Slide Number 10Slide Number 11Slide Number 12Slide Number 13Slide Number 14Slide Number 15Slide Number 16Slide Number 17Slide Number 18Slide Number 19Slide Number 20Slide Number 21Slide Number 22Slide Number 23Slide Number 24Slide Number 25Slide Number 26Slide Number 27