I write application which will be parse XML files. I use SAX parser and here is my SAX handler code:
public class XMLHandler extends DefaultHandler {
private static final String MEASURES = "measures";
private static final String SUGARMEASUREDATE = "sugarMeasureDate";
private static final String SUGARMEASUREVALUE = "sugarMeasureValue";
private static final String UPGYROSCOPEDATE = "upGyroscopeDate";
private static final String UPGYROSCOPEVALUE = "upGyroscopeValue";
private static final String DOWNGYROSCOPEDATE = "downGyroscopeDate";
private static final String DOWNGYROSCOPEVALUE = "downGyroscopeValue";
Boolean currentElement = false;
String currentValue = null;
public static MeasureLists measureLists = null;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("measures")) {
measureLists = new MeasureLists();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
currentElement = false;
if (localName.equals(SUGARMEASUREDATE)) {
measureLists.setSugarDate(currentValue);
}
else if (localName.equals(SUGARMEASUREVALUE)) {
measureLists.setSugarValue(currentValue);
}
else if (localName.equals(UPGYROSCOPEDATE)) {
measureLists.setUpGyroscopeDate(currentValue);
}
else if (localName.equals(UPGYROSCOPEVALUE)) {
measureLists.setUpGyroscopeValue(currentValue);
}
else if (localName.equals(DOWNGYROSCOPEDATE)) {
measureLists.setDownGyroscopeDate(currentValue);
}
else if (localName.equals(DOWNGYROSCOPEVALUE)) {
measureLists.setDownGyroscopeValue(currentValue);
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
public MeasureLists getMeasureLists() {
return measureLists;
}
}
My problem is that this code detects events (start and end tag) properly but variable localName is empty String. I read in documentation that localName is empty if “Namespace processing is not being performed.” My question is what it is mean and how can I handle with it. Thanks for any help and tip.
EDIT
I notice that when I change “localName” variable for “qName” there all things go right and I have no problem. Do you know what it is?
My guess is that your XML uses namespaces, but your SAXParser is not configured for namespace processing (in which case the qualified element, ‘prefix:localName’, is present in the
qNameparameter). If you use JAXP, set thenamespaceAwareproperty on theSAXParserFactorytotrue. To be really sure that your’e processing the correct elements, you should also check that theuriparameter is what you expect (or should expect).You also have a problems with the
charactersmethod. The caharacters() method may be called more than once for each element, even if the element contain only text. What you need to do is to use a StringBuidler to collect the characters in, and use that in the enedELement method.