private static class TreeItemCreationContentHandler extends DefaultHandler {
private TreeItem<String> item = new TreeItem<>();
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
this.item = this.item.getParent();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
TreeItem<String> item = new TreeItem<>(qName);
this.item.getChildren().add(item);
this.item = item;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String s = String.valueOf(ch, start, length).trim();
if (!s.isEmpty()) {
this.item.getChildren().add(new TreeItem<>(s));
}
}
}
public static TreeItem<String> readData(File file) throws SAXException, ParserConfigurationException, IOException {
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
TreeItemCreationContentHandler contentHandler = new TreeItemCreationContentHandler();
reader.setContentHandler(contentHandler);
reader.parse(file.toURI().toString());
TreeItem<String> item = contentHandler.item.getChildren().get(0);
contentHandler.item.getChildren().clear();
return item;
}