実際、これには少なくともスタックが必要になる可能性があります。
クラス(セッター/ゲッターとセクションを追加するメソッド)に明確な変更を加えると(私は願っていますSection
)、このハンドラーはトリックを行うようです:
レイアウトではルート<section>
のすぐ下に複数のタグが許可されているように見えるので<xml>
、結果をに入れて実装しましたList<Section>
。
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class SectionXmlHandler extends DefaultHandler {
private List<Section> results;
private Stack<Section> stack;
private StringBuffer buffer = new StringBuffer();
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if ("xml".equals(localName)) {
results = new ArrayList<Section>();
stack = new Stack<Section>();
} else if ("section".equals(localName)) {
Section currentSection = new Section();
currentSection.setId(attributes.getValue("id"));
stack.push(currentSection);
} else if ("title".equals(localName)) {
buffer.setLength(0);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("section".equals(localName)) {
Section currentSection = stack.pop();
if (stack.isEmpty()) {
results.add(currentSection);
} else {
Section parent = stack.peek();
parent.addSection(currentSection);
}
} else if ("title".equals(localName)) {
Section currentSection = stack.peek();
currentSection.setTitle(buffer.toString());
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
buffer.append(ch, start, length);
}
public List<Section> getResults() {
return results;
}
}