简体   繁体   中英

how to differentiate xml tags that belong to layer1 and those that belong layer2 if they use the same tag name?

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>

免责声明:对android一无所知,但通常这种情况非常适合XML名称空间

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM