Search code examples
javaparsingdatesax

Parsing date from XML with Java


I just don't want to reinvent the wheel if not necessary so I'll ask you the following, what is the easiest ways to parse the following into a Java date using a saxparser extension?

<start-date>
   <year>2012</year>
   <month>04</month>
   <day>10</day>
</start-date>


if (currentQName.equals("start-date")) {
         //return Java date the easiest way possible.
}

My solution involves saving all three than checking all possibilities and I want to avoid that if possible.

Tricky thing is that there are restriction originating from DTD, only YEAR is mandatory, if month is defined, than day is mandatory as well.

Thanks!


Solution

  • StringBuilder buf = new StringBuilder();
    int year;
    int month;
    int day;
    
    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        if (localName.equals("year")) {
            buf.setLength(0);
        } else if (localName.equals("month")) {
            buf.setLength(0);
        } else if (localName.equals("day")) {
            buf.setLength(0);
        }
    }
    
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equals("start-date")) {
           doSomethingWith(year,month,day);
        } else if (localName.equals("year")) {
            year = Integer.parseInt(buf.toString());
        } else if (localName.equals("month")) {
            month = Integer.parseInt(buf.toString());
        } else if (localName.equals("day")) {
            day = Integer.parseInt(buf.toString());
        }
    }
    
    @Override
    public void characters(char chars[], int start, int length)
            throws SAXException {
        buf.append(chars, start, length);
    }