Friday, 22 August 2014

Java SAX is not parsing properly



I would appreciate any help on this. This is my first handler I wrote.


I got I REST Webservice returning XML of links. It has quite simple structure and is not deep. I wrote a handler for this:



public class SAXHandlerLnk extends DefaultHandler {

public List<Link> lnkList = new ArrayList();
Link lnk = null;
String content = null;

@Override
//Triggered when the start of tag is found.
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

if (qName.equals("link")) {
lnk = new Link();
}
}

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("link")) {
lnkList.add(lnk);
}
else if (qName.equals("applicationCode")) {
lnk.applicationCode = content;
}
else if (qName.equals("moduleCode")) {
lnk.moduleCode = content;
}
else if (qName.equals("linkCode")) {
lnk.linkCode = content;
}
else if (qName.equals("languageCode")) {
lnk.languageCode = content;
}
else if (qName.equals("value")) {
lnk.value = content;
}
else if (qName.equals("illustrationUrl")) {
lnk.illustrationUrl = content;
}
}

@Override
public void characters(char[] ch, int start, int length) throws SAXException {
content = String.copyValueOf(ch, start, length).trim();
}
}


Some XML returned can be empty eg. or . When this happens my handler unfortunatelly adds previous value to the Object lnk. So when is empty in XML, I got lnk.illustrationUrl = content; equal to lnk.value.



Link{applicationCode='onedownload', moduleCode='onedownload',...}


In the above example, I would like moduleCode to be empty or null, because in XML it is an empty tag.


Here is the calling class:



public class XMLRepositoryRestLinksFilterSAXParser {

public static void main(String[] args) throws Exception {
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandlerLnk handler = new SAXHandlerLnk();
parser.parse({URL}, handler);

for ( Link lnk : handler.lnkList){
System.out.println(lnk);
}
}
}

No comments:

Post a Comment