dom4j-full.jar 解析 XML
dom4j-full.jar 解析 XML
public Document getDocument() throws DocumentException { SAXReader read=new SAXReader(); return read.read(this.getClass().getResourceAsStream("/course.xml")); } public List<Course> getAllCourse() { List<Course> list=new ArrayList<Course>(); try { Document doc=this.getDocument(); Element root=doc.getRootElement(); List<Element> courseNodes=root.elements("course"); for (Element courseNode:courseNodes) { Course course=new Course(); course.setName(courseNode.elementTextTrim("name")); course.setDate(courseNode.elementTextTrim("date")); course.setDesc(courseNode.elementTextTrim("desc")); list.add(course); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }
<?xml version="1.0" encoding="UTF-8"?> <courses> <course> <name>JAVASE</name> <date>23</date> <desc>JAVA语言入门课程</desc> </course> <course> <name>JAVAEE</name> <date>31</date> <desc>JAVA语言高级课程</desc> </course> </courses>