cowsay
cowsay

Reputation: 1332

XmlPullParser - Pull from elements with a specific parent element

Consider this XML. It describes a list of people and the cars they own.

<People>
    <Person id="100">
        <Name>Bob</Name>
        <Cars>
            <Car>
                <Make>Toyota</Make>
                <Model>Celica</Model>
            </Car>
        </Cars>
    </Person>
    <Person id="101">
        <Name>Jim</Name>
        <Cars>
            <Car>
                <Make>Ford</Make>
                <Model>Pinto</Model>
            </Car>
            <Car>
                <Make>Dodge</Make>
                <Model>Viper</Model>
            </Car>
        </Cars>
    </Person>
</People>

I have already created a parser that will go through and grab:

ID: 100, Name: Bob
ID: 101, Name: Jim

But I am struggling to break this down and grab the nested elements which are a child of a specific parent.

while (eventType != XmlPullParser.END_DOCUMENT) {
    String name = null;
    switch (eventType) {
        case XmlPullParser.START_DOCUMENT:
            // do something
            break;                      
        case XmlPullParser.START_TAG:                               
            name = parser.getName();
            if (name.equalsIgnoreCase("Cars")) {                    

                // how do i restrict this to only cars under person with ID 101?

            } 

Let's say I only want to find out what kind of cars Jim has. I know Jim's ID is 101, but how do I restrict a XmlPullParser loop to ONLY look at the Cars element when the parent Person element has an id of 101?

Upvotes: 1

Views: 1304

Answers (1)

cy3er
cy3er

Reputation: 1699

You can use flags to know where the parser is currently, for instance:

boolean personFound = false;
boolean carsFound = false;
while (eventType != XmlPullParser.END_DOCUMENT) {
    if (XmlPullParser.START_TAG && parser.getName().equals("Person") && parser.getAttributeValue(0).equals("101")) {
        personFound = true;
    }
    if (personFound && XmlPullParser.START_TAG && parser.getName().equals("Cars")){
        carsFound = true
    }
    if (carsFound) {
        // Do something useful
    }
    if (carsFound && XmlPullParser.END_TAG && parser.getName().equals("Cars"){
        break;
    }
    eventType = parser.next();
}

Upvotes: 3

Related Questions