Wolvern
Wolvern

Reputation: 23

Seemingly random SAX output error

I'm creating an Android application that is supposed to use SAX (javax.xml.parsers.SAXParser) to parse an XML file containing information about various locations, so that these locations can then be displayed as points on a map; unfortunately I'm having trouble with my parser.

The XML file is made up of over 1000 repeating groups that look like this:

<Placemark id="00001">
  <name>Place name</name>
  <address>Place address</address>
  <ExtendedData>
    <Data name="postcode">
      <value>Place postcode</value>
    </Data>
  </ExtendedData>
  <Point>
    <coordinates>-0.000000,51.000000</coordinates>
  </Point>
</Placemark>

My XML handler checks to see what the name of the current element is and then adds that element's value to a relevant list, i.e.

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

    if(localName.equals("placemark")) list.setPlaceID(attributes.getValue("id"));
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {

    if(localName.equals("name")) list.setName(currentValue);
    else if(localName.equals("address")) list.setAddress(currentValue);
    else if(localName.equals("value")) list.setPostCode(currentValue);
    else if(localName.equals("coordinates")) System.out.println(currentValue);  
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException{

    currentValue = new String(ch, start, length);
}

This successfully handles 99.9% of cases, but for some reason I cannot figure out there are some particular XML coordinate elements that produce an unexpected output when parsed, for example:

  1. <coordinates>-0.328459,51.604121</coordinates> produces 4121 rather than -0.328459,51.604121

  2. <coordinates>-0.060226,51.602341</coordinates> produces 26,51.602341 rather than -0.060226,51.602341

Even more confusingly, if the offending elements are isolated then they can be parsed without a problem. It's only when a very large number are to be parsed that a select few cause this issue.

Are there any obvious explanations that might explain these results?

Upvotes: 2

Views: 100

Answers (1)

Pragalathan  M
Pragalathan M

Reputation: 1781

use

currentValue += new String(ch, start, length);

and initialize it to

currentValue = ""; 

in endElement after using.

The reason is that the content of a tag is send in multiple chunks wherever there is a word break. So you need to concatenate it.

Upvotes: 2

Related Questions