What are you using booleans for? To track nesting?
I recently implemented this using an enumeration for each element. The code works, but this is a rough approximation of this from the top of the head:
enum Element {
ROOT,
DONT_CARE,
RootElement( "root" ROOT),
AnElement( "anelement"),
AnotherElement( "anotherelement"),
AChild( "child", AnElement),
AnotherChild( "child", AnotherElement);
Element() {...}
Element(String tag, Element ... parents) {...}
}
class MySaxParser extends DefaultHandler {
Map<Pair<Element, String>, Element> elementMap = buildElementMap();
LinkedList<Element> nestingStack = new LinkedList<Element>();
public void startElement(String namespaceURI, String sName, String qName, Attributes attrs) {
Element parent = nestingStack.isEmpty() ? ROOT : nestingStack.lastElement();
Element element = elementMap.get(pair(parent, sName));
if (element == null)
element = elementMap.get(DONT_CARE, sName);
if (element == null)
throw new IllegalStateException("I did not expect <" + sName + "> in this context");
nestingStack.addLast(element);
switch (element) {
case RootElement: ...
case AnElement: ...
case AnotherElement: ...
case AChild: ...
case AnotherChild: ...
default:
}
}
public void endElement(String namespaceURI, String sName, String qName) {
Element element = nestingStack.removeLast();
if (!element.tag.equals(sName)) throw IllegalStateException();
switch (element) {
...
}
}
private Map<Pair<Element, String>, Element> buildElementMap() {
Map<Pair<Element, String>, Element> result = new LinkedHashMap<Pair<Element, String>, Element>();
for (Element element: Element.values()) {
if (element.tag == null) continue;
if (element.parents.length == 0)
result.put(pair(DONT_CARE, element.tag), element);
else for (Element parent: element.parents) {
result.put(pair(parent, element.tag), element);
}
}
return result;
}
private <A,B> Pair<A,B> pair(A a, B b) {
return new Pair<A, B>(a, b);
}
private static class Pair<A,B> {
final A a;
final B b;
Pair(A a, B b){ this.a = a; this.b = b;}
public boolean equals(Object o) {...};
public int hashCode() {...};
}
}
Edit:
XML . startElement, Element 1) 2) , sName, , , Element. Pair 2 .
-, XML , Element. :
<root>
<anelement>
<child>Data pertaining to child of anelement</child>
</anelement>
<anotherelement>
<child>Data pertaining to child of anotherelement</child>
</anotherelement>
</root>
, , , <child> . Element , .