You are on page 1of 27

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 <tagElements> 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
<employee id= title= >...</employee>
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=72d6aa49787d4118b
a5f4f30fe913628&displaylang=en
<?xml version="1.0" encoding="utf8" ?>
<Employees xmlns="http://Employees">
<Employee id="12615" title="Architect">
<! Thi s i s a comment >
<Name>
<First>Nancy</First>
<Middle>J.</Middle>
<Last>Davolio</Last>
</Name>
<Street>507 20th Ave. E. Apt. 2A</Street>
<City>Seattle</City>
<Zip>98122</Zip>
<Country>
<Name>U.S.A.</Name>
</Country>
<Office>5/7682</Office>
<Phone>(206) 5559857</Phone>
<Photo>Photo.jpg</Photo>
</Employee>
<Employee>
. . .
</Employee>
</Employees>
Element: Street
Attributes: id, title
<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
attributeFormDefault="unqualified" targetNamespace="http://Employees" xmlns="http://Employees">

<xs:complexType name="Country">
<xs:sequence>
<xs:element name="Name" type="xs:string" default="U.S.A." />
</xs:sequence>
<xs:attribute name="code" type="xs:language">
<xs:annotation>
<xs:documentation>The registered IANA country code of the format xxxx. For example: enus.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>

<xs:simpleType name="City">
<xs:restriction base="xs:string">
<xs:minLength value="1" />
<xs:maxLength value="50" />
</xs:restriction>
</xs:simpleType>

<xs:simpleType name="Zip">
<xs:restriction base="xs:positiveInteger">
<xs:maxInclusive value="99999" />
<xs:minInclusive value="00001" />
</xs:restriction>
</xs:simpleType>

<xs:simpleType name="EmployeeID">
<xs:annotation>
<xs:documentation>The ITG assigned 5 digit employee identification</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:length value="5" />
</xs:restriction>
</xs:simpleType> 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)
<?xml version="1.0" encoding=utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>

<gcPlace gcName="Manakiki Golf Course" gcCity="Willoughby Hills" gcState="Ohio" />

<Placemark>
<name par="4" yards="390" >Tee Hole 1</name>
<Point>
<coordinates>81.4324182271957,41.5984273639879,0</coordinates>
</Point>
</Placemark>

<Placemark>
<name>Front of Green Hole 1</name>
<Point>
<coordinates>81.433182656765,41.5955730479591,0</coordinates>
</Point>
</Placemark>

<Placemark>
<name>Middle of Green Hole 1</name>
<Point>
<coordinates>81.4331665635109,41.5954647298964,0</coordinates>
</Point>
</Placemark>

</Document>
</kml>
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:

<name par="4" yards="390" >Tee Hole 1</name>


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)
<?xml ver si on="1.0" encoding="utf-8"?>
<Li near Layout xml ns: andr oi d="http://schemas.android.com/apk/res/android"
andr oi d: or i ent at i on="vertical"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="fill_parent">

<But t on
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: l ayout _gr avi t y="center"
andr oi d: l ayout _wi dt h="wrap_content"
andr oi d: t ext ="Read XML data"
andr oi d: i d="@+id/btnReadXml" />

<Scr ol l Vi ew andr oi d: i d="@+id/ScrollView01"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: l ayout _wei ght ="2">

<Text Vi ew andr oi d: i d="@+id/txtMsg"
andr oi d: l ayout _wi dt h="fill_parent"
andr oi d: l ayout _hei ght ="wrap_content"
andr oi d: backgr ound="#ff0000ff"
andr oi d: t ext St yl e="bold"/>

</ Scr ol l Vi ew>

</ Li near Layout >
SAX
Simple API for XML
15
18. Android Reading XML Files
XML Data
15
Example 2. Reading a Resource KML File (code)
/ / demonst r at es t he r eadi ng of XML r esour ce f i l es. I n t hi s case
/ / cont ai ni ng mappi ng dat a ( kml ) hol di ng i nner el ement s as wel l
/ / as common <node> t ext </ node> t ags.
/ / - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
package ucr.xmlreading;

import . . .

public class Main extends Activity {

private TextView txtMsg;
But t on bt nGoPar ser ;
@Over r i de
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
set Cont ent Vi ew( R. l ayout . main);
t xt Msg = ( Text Vi ew) f i ndVi ewByI d( R. i d. txtMsg);
bt nGoPar ser = ( But t on) f i ndVi ewByI d( R. i d. btnReadXml);
bt nGoPar ser . set OnCl i ckLi st ener ( new View.OnClickListener() {
@Over r i de
public void onClick(View v) {
bt nGoPar ser . set Enabl ed( false);
Xml Pul l Par ser par ser = get Resour ces( ) . get Xml ( R. xml . manakiki_hole1_v2);
St r i ngBui l der st r i ngBui l der = new StringBuilder();
St r i ng nodeText = "";
St r i ng 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) {
event Type = par ser . next ( ) ;
if(eventType == XmlPullParser.START_DOCUMENT) {
st r i ngBui l der . append( " St ar t document \ n" ) ;
} else if(eventType == XmlPullParser.END_DOCUMENT) {
st r i ngBui l der . append( " End document \ n" ) ;

} else if(eventType == XmlPullParser.START_TAG) {
nodeName = par ser . get Name( ) ;
st r i ngBui l der . append( " St ar t t ag: \ t " + par ser . get Name( ) + " \ n" ) ;
i nner At t r i but es( par ser , st r i ngBui l der ) ;

} else if(eventType == XmlPullParser.END_TAG) {
st r i ngBui l der . append( " End t ag: \ t " + par ser . get Name( ) + " \ n" ) ;

} else if(eventType == XmlPullParser.TEXT) {
if (nodeName.equals("name")) stringBuilder.append("\n");
nodeText = par ser . get Text ( ) ;
st r i ngBui l der . append( " Text : \ t \ t " + par ser . get Text ( ) + " \ n" ) ;
t okeni zeText ( par ser , st r i ngBui l der , nodeName) ;
}
t xt Msg. set Text ( st r i ngBui l der . t oSt r i ng( ) ) ;
}
}catch(Exception e) {
Log. e("<<PARSING>>", e.getMessage());
}
}
}) ;
}/ / onCr eat e
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) {
/ / t r yi ng t o det ect i nner el ement s nest ed ar ound gcDat a t ag
St r i ng name = par ser . get Name( ) ;
if (!name.equals("gcPlace")) return;
St r i ng gcName = null;
St r i ng gcCi t y = null;
St r i ng gcSt at e= null;
/ / Pr ocessi ng a f r agment of t he t ype:
/ / <gcPl ace gcName=" Manaki ki GC" gcCi t y=" Wi l l oughby" gcSt at e=" OH" ></ gcPl ace>
if((name != null) && name.equals("gcPlace")) {
int size = parser.getAttributeCount();
for(int i = 0; i < size; i++) {
St r i ng at t r Name = par ser . get At t r i but eName( i ) ;
St r i ng at t r Val ue = par ser . get At t r i but eVal ue( i ) ;
if((attrName != null) && attrName.equals("gcName")) {
gcName = at t r Val ue;
} else if ((attrName != null) && attrName.equals("gcCity")) {
gcCi t y = at t r Val ue;
} else if ((attrName != null) && attrName.equals("gcState")) {
gcSt at e = at t r Val ue;
}
}
if((gcName != null) && (gcCity != null) && (gcState != null) ) {
st r i ngBui l der . append( " <<I NNER>> \ t : "
+ gcName + " , "
+ gcCi t y + " , "
+ gcSt at e + " \ n" ) ;
t xt Msg. set Text ( " <<I NNER>> \ t : " + st r i ngBui l der . t oSt r i ng( ) + " \ n" ) ;
}
}
}/ / i nner El ement s
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){
/ / i nt er pr et i ng t ext encl osed i n a coor di nat es t ag
St r i ng t ext = par ser . get Text ( ) ;
if ((text==null) || (!nodeName.equals("coordinates"))) return;

/ / par si ng <coor di nat es> l at i t ude, l ongi t ude, al t i t ude </ coor di nat es>
St r i ng [ ] l oc = t ext . spl i t ( " , " ) ;
t ext = " <<LOC>> " + nodeName
+ " Lon: " + l oc[ 0] + " Lat : " + l oc[ 1] + " \ n" ;
st r i ngBui l der . append( t ext ) ;
t xt Msg. set Text ( st r i ngBui l der ) ;
}/ / t okeni zeBui l der

}/ / Mai n

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)
<?xml version="1.0" encoding=utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>

<gcPlace gcName="Manakiki Golf Course" gcCity="Willoughby Hills" gcState="Ohio" />

<Placemark>
<name par="4" yards="390" >Tee Hole 1</name>
<Point>
<coordinates>81.4324182271957,41.5984273639879,0</coordinates>
</Point>
</Placemark>

<Placemark>
<name>Front of Green Hole 1</name>
<Point>
<coordinates>81.433182656765,41.5955730479591,0</coordinates>
</Point>
</Placemark>

<Placemark>
<name>Middle of Green Hole 1</name>
<Point>
<coordinates>81.4331665635109,41.5954647298964,0</coordinates>
</Point>
</Placemark>

</Document>
</kml>
21
18. Android Reading XML Files
XML Data
21
Example 3. Reading an XML file from the SD card (code)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#ff0000ff">

<Button
android:id="@+id/button1"
android:layout_width="106dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Go" />

<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.62" >

<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1" >

<requestFocus />
</EditText>

</LinearLayout>
</ScrollView>

</LinearLayout>
package csu.matos;

import . . .

public class ReadingXMLVersion1Activity extends Activity {
Button btnGo;
EditText txtMsg;

XmlPullParser parser;

String elementName;
String attributeName;
String attributeValue;

StringBuilder str;

@Over r i de
public void onConfigurationChanged(Configuration newConfig) {
/ / needed t o avoi d r e- st ar t i ng app on or i ent at i on 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 <activity > 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){
/ / cal cul at i ng di st ance ( yar ds) bet ween t wo coor di nat es
int intDistance = 0;
double distance = 0;
Locat i on l ocat i onA = new Location("point: Here");
l ocat i onA. set Lat i t ude( Doubl e. parseDouble(aLatitude));
l ocat i onA. set Longi t ude( Doubl e. parseDouble(aLongitude));

Locat i on l ocat i onB = new Location("point: F/M/B Green");
l ocat i onB. set Lat i t ude( Doubl e. parseDouble(bLatitude));
l ocat i onB. set Longi t ude( Doubl e. parseDouble(bLongitude));

di st ance = l ocat i onA. di st anceTo( l ocat i onB) * METER_TO_YARDS;
i nt Di st ance = ( int) Math.round(distance);
return intDistance;
}

}/ / Gol f Mar ker
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

You might also like