Kyle V.
Kyle V.

Reputation: 4782

Android Dev: Parsing a XML file

Here is a snippet from the XML file I am trying to parse:

<Item xsi:type="TextureItem" Name="Texture_0044" Visible="true">
    <Position>
        <X>240</X>
        <Y>432</Y>
    </Position>
    <CustomProperties>
        <Property Name="type" Type="string" Description="slot_rectangle">
            <string />
        </Property>
    </CustomProperties>
    <Rotation>0</Rotation>
    <Scale>
        <X>1</X>
        <Y>1</Y>
    </Scale>
    <TintColor>
        <R>255</R>
        <G>255</G>
        <B>255</B>
        <A>255</A>
        <PackedValue>4294967295</PackedValue>
    </TintColor>
</Item>

I'm using an XmlResourceParser object to parse the XML file and here is my code so far:

XmlResourceParser xrp = context.getResources().getXml(R.xml.level_1);

int eventType = xrp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
    if(eventType == XmlPullParser.START_DOCUMENT) {
        //System.out.println("Start document");
    } else if(eventType == XmlPullParser.START_TAG) {
        //System.out.println("Start tag "+xrp.getName());
        if (xrp.getName().equals("Item")) {
            //...
        }
    } else if(eventType == XmlPullParser.END_TAG) {
        //System.out.println("End tag "+xrp.getName());
    } else if(eventType == XmlPullParser.TEXT) {
        //System.out.println("Text "+xrp.getText());
    }
    eventType = xrp.next();
}
System.out.println("End document");
xrp.close();

What I'm trying to do is have it so that every time a Item tag is found it will get the "Description" value of the Property tag, the text values of the X and Y tags inside the Position tag, and the text value of the Rotation tag and nothing more.

Right now I'm considering where it says if (xrp.getName().equals("Item")) just copying and pasting the outside parsing code to the inside of that if condition and then going up and down in levels getting the values I want until the END_TAG for the Item tag event occurs, but that seems very inefficient and confusing.

What I want sort of is like a xrp.Item.Position.X.getText() sort of deal if you know what I mean, does something like that exist?

Thanks!

Upvotes: 0

Views: 466

Answers (1)

dmon
dmon

Reputation: 30168

You're on the right track. Just create an object model that maps to what you expect and fill it in as you parse the XML. You'll be better off having a light-weight representation of the data instead of trying to use xpath as you need values.

Upvotes: 2

Related Questions