CS 175/286 - Lecture 6

Cover page image

Cay S. Horstmann

Today's Lecture

XML Parsing

SAX Parsing

SAX Parsing Example

public class Question implements Serializable {
    private String text;
    private List<String> choices = new ArrayList<String>();
    private int correctChoice;

    public void readFromXml(InputStream in) throws IOException {
        class QuestionHandler extends BasicHandler {
            @Override
            public void startElement(String uri, String localName,
                    String qName, Attributes attributes) throws SAXException {
                super.startElement(uri, localName, qName, attributes);
                if ("true".equals(attributes.getValue("value")))
                    correctChoice = choices.size(); 
            }
            @Override
            public void endElement(String uri, String localName, String qName)
                    throws SAXException {
                if (qName.equals("text")) text = lastString();
                else if (qName.equals("choice")) choices.add(lastString());
            }
        }
        
        try {       
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser(); 
            parser.parse(in, new QuestionHandler());
        } catch (Exception ex) {
            IOException ioEx = new IOException(ex.getMessage());
            ioEx.initCause(ex);
            throw ioEx;
        }       
    }
	  ...
}

Lecture 6 Quiz 1

Put your answer into Piazza.

What is NOT true about RSS parser code example in Android Recipes Section 3.8?

  1. If the author had used the BasicHandler convenience class, the startElement method would have been shorter.
  2. The channel element must be handled in the startElement method.
  3. The title element must be handled in the endElement method.
  4. The inItem flag is necessary.

Lecture 6 Quiz 2

What is NOT true about the XML pull parser implementation of the RSS parser code?

  1. It is longer than the SAX implementation.
  2. Its structure is more aligned with the structure of the data to be parsed.
  3. Unlike the SAX parser, the pull parser checks that the document is valid.
  4. The statement
    if (parser.getEventType() != XmlPullParser.START_TAG) {
        continue;
    }
    is necessary.

Reading Before Next Class

Lab

Reading XML