实现ElementHandler接口
public class MyHandler implements ElementHandler {
@Override
public void onStart(ElementPath elementPath) {
}
@Override
public void onEnd(ElementPath elementPath) {
elementPath.getCurrent().detach();
}
}
ElementPath获取一些信息
public static int getLevel(ElementPath path) {
return path.getPath().split("/").length - 1;
}
public static String getElementName(Element element) {
return element.getName();
}
public static String getAttribute(Element element) {
return element.attribute("attribute-name");
}
public static String getText(Element element) {
return element.getText();
}
解析示例
<root>
<book id="1">
<name>菜鸟编程</name>
<describe>针对菜鸟编程学习</describe>
</book>
<book id="2">
<name>老鸟编程</name>
<describe>针对老鸟编程学习</describe>
</book>
</root>
@Data
public class Book {
private int id;
private String name;
private String describe;
}
public class BookHandler implements ElementHandler {
private Book book;
@Override
public void onStart(ElementPath elementPath) {
level = getLevel(elementPath)
switch(level):
case 1:
case 2:
book = new Book();
book.setId();
case 3:
}
@Override
public void onEnd(ElementPath elementPath) {
level = getLevel(elementPath)
switch(level):
case 1:
case 2:
saveDB(book);
book = null;
case 3:
String name = getAttribute("name");
String describe = getAttribute("describe");
book.setName(name);
book.setDescribe(describe);
elementPath.getCurrent().detach();
}
}
BookHandler bookHandler = new BookHandler();
SAXReader reader = new SAXReader();
reader.setDefaultHandler(bookHandler);
reader.read(new File(xmlPath));