Parsing XML Files with Xml ResourceParser

The mock score files have a very simple schema with only two tags: <scores> and <score>. You want to find each <score> tag and extract its username, rank, and score attributes. Because you can assume a small amount of data, you can implement your parsing routing by using a simple while() loop to iterate through the events by using the next() method, as follows:

boolean bFoundScores = false;

// Find Score records from XML

while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) {

// Get the name of the tag (eg scores or score) String strName = scores.getName(); if (strName.equals("score")) { bFoundScores = true;

String scoreValue = scores.getAttributeValue(null, "score"); String scoreRank = scores.getAttributeValue(null, "rank"); String scoreUserName =

scores.getAttributeValue(null, "username"); insertScoreRow(scoreTable, scoreValue, scoreRank, scoreUserName);

eventType = scores.next();

Within the loop, you watch for the START_TAG event. When the tag name matches the <score> tag, you know you have a piece of score data. You then extract the data by using the getAttributeValue() method. For each score you find, you add a new TableRow control to the appropriate TableLayout control (in the appropriate tab).

0 0

Post a comment