import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
class Department {
private String number;
private String name;
private List<Integer> products;
public Department(String number, String name) {
this.number = number;
this.name = name;
this.products = new ArrayList<>();
}
public void setProducts(List<Integer> products) {
this.products = products;
}
public String toString() {
return String.format("Name: %s\nNumber: %s\nProducts: %s\n", name, number, products);
}
}
public class SAXHandler extends DefaultHandler {
private List<Department> departments;
private List<Integer> products;
private Department currentDepartment;
public SAXHandler() {
this.departments = new ArrayList<>();
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(qName.equals("department")) {
String name = attributes.getValue("name");
String number = attributes.getValue("number");
products = new ArrayList<>();
currentDepartment = new Department(name, number);
}
if(qName.equals("product")) {
String id = attributes.getValue("id");
products.add(Integer.valueOf(id));
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equals("department")) {
currentDepartment.setProducts(products);
departments.add(currentDepartment);
}
}
public List<Department> getResult() {
return departments;
}
public static void main(final String args[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
SAXHandler handler = new SAXHandler();
saxParser.parse("test.xml", handler);
handler.getResult().stream().forEach(System.out::println);
}
catch(SAXException ex) {}
catch(ParserConfigurationException ex) {}
catch(IOException ex) {}
}
}
Map<String, String> attrs = new HashMap<>();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
String name = attributes.getValue("name");
String value = attributes.getValue("size");
attrs.put(name, value);
}
class Vehicle {
public speedUp (int newSpeed) {
speed = newSpeed;
}
}
class Car extends Vehicle {
private boolean opened = false;
public void openDoor {
opened = true;
}
}
class Tank extends Vehicle {
private ammo = 10;
public void fire(Vehicle enemy) {
ammo -= 1;
}
}