views:

26

answers:

1

I am trying to parse an xml file using SAX with Android and the problem is that the function characters(...) is getting called multiple times with what appears to be the same data just offset by a few characters.

As you can tell from the output below the first time it gets called with "\talabama" and the second time it gets called with "labama". I am not sure as to why it is doing this but if anyone could help that would be awesome.

XML Input:

<?xml version="1.0"  encoding="utf-8"?>
<dir><name>.</name>
    <dir><name>alabama</name>
        <dir><name>sub_dir_name</name>
            <file><name>file_name.kml</name></file>
        </dir>
    </dir>
</dir>

Output of Characters(...):

10-27 23:04:47.033: DEBUG/LocationHandler(10299):     
10-27 23:04:49.000: DEBUG/LocationHandler(10299):     alabama
10-27 23:04:51.835: DEBUG/LocationHandler(10299): labama
10-27 23:04:52.129: DEBUG/LocationHandler(10299): labama        abama
10-27 23:04:52.408: DEBUG/LocationHandler(10299): labama        abamasub_dir_name
10-27 23:04:52.519: DEBUG/LocationHandler(10299): ub_dir_name
10-27 23:04:52.649: DEBUG/LocationHandler(10299): ub_dir_name            _dir_name
10-27 23:04:52.809: DEBUG/LocationHandler(10299): ub_dir_name            _dir_namefile_name.kml
10-27 23:04:52.989: DEBUG/LocationHandler(10299): ile_name.kml
10-27 23:04:53.158: DEBUG/LocationHandler(10299): ile_name.kml        le_name.kml
10-27 23:04:53.358: DEBUG/LocationHandler(10299):     le_name.kml
10-27 23:04:53.529: DEBUG/LocationHandler(10299):     le_name.kml        le_name.kml
10-27 23:04:53.698: DEBUG/LocationHandler(10299):     le_name.kml

Handler Overides:

@Override
public void startElement(String uri, String localName, String qName,
    Attributes attributes) throws SAXException
{
}

@Override
public void endElement(String uri, String localName, String qName)
    throws SAXException
{
  _currentElementValue = "";
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException
{
  _currentElementValue += new String(ch);

  Log.d(TAG, _currentElementValue);
}
A: 

I see an obvious problem in your code, in the characters() method, you cannot create a string blindly with just the char array. It should be like this below :



public void characters(char[] ch, int start, int length) throws SAXException
{
  _currentElementValue += new String(ch, start, length);

  Log.d(TAG, _currentElementValue);
}


You may want to learn more on how SAX parsing works.

Ramp
You kind sir are awesome! I am really new to Java in general so I have a lot to learn.
Jon W. Jones
There are lots of examples out there. here is one : http://www.rgagnon.com/javadetails/java-0408.html
Ramp