roegonnatin
New Member
I've been parsing XML like this for years, and I have to admit when the number of different element becomes larger I find it a bit boring and exhausting to do, here is what I mean, sample dummy XML:\[code\]<?xml version="1.0"?><Order> <Date>2003/07/04</Date> <CustomerId>123</CustomerId> <CustomerName>Acme Alpha</CustomerName> <Item> <ItemId> 987</ItemId> <ItemName>Coupler</ItemName> <Quantity>5</Quantity> </Item> <Item> <ItemId>654</ItemId> <ItemName>Connector</ItemName> <Quantity unit="12">3</Quantity> </Item> <Item> <ItemId>579</ItemId> <ItemName>Clasp</ItemName> <Quantity>1</Quantity> </Item></Order>\[/code\]This is relevant part (using sax) :\[code\]public class SaxParser extends DefaultHandler { boolean isItem = false; boolean isOrder = false; boolean isDate = false; boolean isCustomerId = false; private Order order; private Item item; @Override public void startElement(String namespaceURI, String localName, String qName, Attributes atts) { if (localName.equalsIgnoreCase("ORDER")) { order = new Order(); } if (localName.equalsIgnoreCase("DATE")) { isDate = true; } if (localName.equalsIgnoreCase("CUSTOMERID")) { isCustomerId = true; } if (localName.equalsIgnoreCase("ITEM")) { isItem = true; } } public void characters(char ch[], int start, int length) throws SAXException { if (isDate){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); String value = http://stackoverflow.com/questions/15626686/new String(ch, start, length); try { order.setDate(formatter.parse(value)); } catch (ParseException e) { e.printStackTrace(); } } if(isCustomerId){ order.setCustomerId(Integer.valueOf(new String(ch, start, length))); } if (isItem) { item = new Item(); isItem = false; } }}\[/code\]I'm wondering is there a way to get rid of these hideous booleans which keep growing with number of elements. There must be a better way to parse this relatively simple xml. Just by looking the lines of code necessary to do this task looks ugly. Currently I'm using SAX parser, but I'm open to any other suggestions (other than DOM, I can't afford in memory parsers I have huge XML files).