<database>
<store id=”MTV”>
<address>1600 Amphitheater Pwky., Mountain View, CA 94043</address>
<orders>
<order id=”12345”>
<status>backordered</status>
<items>
<item>Nexus 5</item>
<item>Hello Kitty Phone Case</item>
</items>
</order>
<order id=”ABCDE”>
<status>delivered</status>
<items>…</items>
</order>
…
</orders>
</store>
<store id=”SFO”>…</store>
…
</database>
public abstract class XMLParser {
public XMLParser() {
…
}
public void Parse(InputStream input) {
// Implemented by the library, contains calls to StartElement,
// EndElement and Content.
…
}
// Implemented by you.
protected abstract void StartElement(String tag,
Map<String, String> attributes);
protected abstract void EndElement(String tag);
protected abstract void Content(String text);
}
public class DataBase{
public List<Store> getStores(){
}
}
public class Store {
public String id;
private List<Order> orders;
public Store(String id){
this.id = id;
}
public List<Order> getOrders(){
return orders;
}
}
public class Order {
public String id;
private List<Item> items;
public Order(String id){
this.id = id;
}
public List<Item> getItems(){
return items;
}
}
public class Item{
public String name;
public Item(String name){
this.name = name;
}
}
public enum ELEMENTS{DATABASE(“database”), STORE(“store”), ORDER(“order”), ITEM(“item”)}
public class MyXMLParser extends XMLPareser {
Database database = null;
Map<String, Store> storeMap = new TreeMap<String, Store>();
Stack<Object> stack = new Stack<Object>();
protected void StartElement(String tag,
Map<String, String> attributes) {
ELEMENTS elTag = new ELEMENTS(tag);
switch(elTag){
DATABASE:
database = new DataBase();
stack.push(database);
break;
STORE:
String id = attributes.get(“id”);
Store newStore = new Store(id);
stack.peek().add(newStore);
storeMap.put(id, newStore);
stack.push(newStore);
ORDER:
String id = attributes.get(“id”);
Order newOrder = new Order(id); stack.peek().add(newStore);
stack.push(newOrder);
ITEM:
Item newItem = new Item();
}
}
protected void EndElement(String tag) {
stack.pop();
}
protected void Content(String text) {
if(isXMLTag(text)){
StartElement
}
}
private boolean isXMLTag(String text){
//TODO
}
private
}
Did not finish the actual coding implementation, but the interviewer said this is the right approach to resolve this problem.
Most likely I will get an on-site opportunity.