Sashu Sashu -3 years ago 72
Android Question

How/when to use XmlPullParser.require() method

Android newbie disclaimer: I'm an Android newbie, please go easy on me.

I'm pulling my hair out trying to understand Android's Parsing XML Data example, specifically their usage of parser.require() - under the heading "Read the Feed".

Yes, I've read the documentation for XmlPullParser. I must be an idiot, because I can't make sense of it.

I've also dug around these SO forums and wasn't successful in finding an answer I could personally parse :-)

Okay, so it throws an exception if the parameters passed in are not met. How does that help me when it appears to be applied only to a single element?

How am I supposed to know which parameters to pass in to the method?

Is it always necessary? Or just sometimes? Why?

Should I be using this method whenever I parse XML? Where? Why?

Their example seems to be addressing the "feed" tag at the beginning of the XML feed, but they don't seem to address the "title" tag immediately following. Why would they assert the "feed" tag but not the following "title" tag?

Oh my god I'm so confused.

My frustration with developing for Android is growing beyond measure, and this one little issue is about to send me over the edge. If anyone could please explain in simple terms to me why use the .require() method, and when it's appropriate, I would be forever grateful.

I have no sample code of my own to post here since all I'm doing is reading and trying to understand the example code.

Thanks in advance to all that try to help me with this.

Answer Source

Right after posting this question I think I figured out how .require() works. Take the following code snippet from

parser.require(XmlPullParser.START_TAG, ns, "feed");
while ( != XmlPullParser.END_TAG) {
    if (parser.getEventType() != XmlPullParser.START_TAG) {
    String name = parser.getName();
    // Starts by looking for the entry tag
    if (name.equals("entry")) {
    } else {

...what I'm taking away from this is that by using .require() we're setting our cursor to the START_TAG of the "feed" element - the top level element - and then we can drop into a loop until we finally hit the END_TAG of the feed element we originally queued up to!

So, .require() not only verifies the entry point for an xml element, but it also informs the parser of which element you're entering so you can iterate through it until you hit the closing tag for that specific element.

Easier to understand than I gave credit for - sorry for the initial whiny post!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download