实际上,您可能至少需要一个堆栈。
通过(我希望)对您的类(setter/getter 和添加部分的方法)进行明确的更改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;
}
}