views:

26

answers:

2

in my xml file,
i have same tag name used at different place (layer1 and layer2),
how can i differenciate tags named "<tile gid ="int">" from layer1 and layer2 ?
i need to process them differently depending if they belong to layer1 or layer2...
here's a small sample of my parser and my xml file:

// =================
// xml parser sample
// =================
XmlResourceParser xrp = (XmlResourceParser) ctx.getResources().getXml(R.xml.castle);
  while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) 
  {
    if (xrp.getEventType() == XmlResourceParser.START_TAG) 
    {
      String s = xrp.getName();
      if (s.equals("tile")) 
      {
        int a = xrp.getAttributeIntValue(null, "gid", 0);
        // process a
      }
    }
  }


// ===============
// xml file sample:
// ===============
<layer name="layer1">
  <data>
    <tile gid="1"/>
    <tile gid="2"/>
    ...
  </data>
</layer>
<layer name="layer2">
  <data>
    <tile gid="1"/>
    <tile gid="2"/>
    ...
  </data>
</layer>
A: 

Disclaimer: Don't know anything about android, but usually this kind of a situation is a a good fit for XML namespaces

dpb
A: 

Your parser code will have to remember which sort of layer it's currently in at the time of the START_TAG event for a tile tag.

One way to do this is to create a field String currentLayer; and somewhere in your code have code segments resembling

if (xrp.getEventType() == XmlResourceParser.END_TAG) 
{
  String s = xrp.getName();
  if (s.equals("layer")) 
  {
    currentLayer = null;  // or something ...
  }
}

and

if (xrp.getEventType() == XmlResourceParser.START_TAG) 
{
  String s = xrp.getName();
  if (s.equals("layer")) 
  {
    currentLayer = xrp.getAttributeValue(null, "name", 0);
  }
}

Then in your code dealing with the tile tag, you'll use that field to decide which action to take with something resembling

if (xrp.getEventType() == XmlResourceParser.START_TAG) 
{
  String s = xrp.getName();
  if (s.equals("tile")) 
  {
    int a = xrp.getAttributeIntValue(null, "gid", 0);
    if ("layer1".equals(currentLayer) {
        // process layer1 tile.
    }
    else if ("layer2".equals(currentLayer) {
        // process layer2 tile.
    }
    else {
        // handle occurrence of tile outside layer.
    }
  }
}

This is not necessarily the best approach, especially if it leads to huge nested if-else constructs, but this might get you started.

A better approach might be to have a field for a delegate that handles tiles, set it to an appropriate "tile-processor" object (which you'll have to define as a separate class) during the start event handling for the layer tag and use it in the handling of the tile tag. But that's harder to put in code snippets.

Don Roby
dpb and donroby, both answer were very usefuli have it working nowthanks !
freeaks
@freeaks - Good to hear! If you accept one of the answers or even post and accept your own with how you actually solved the problem, it will help all.
Don Roby