JDOM操作XML

来源:互联网 发布:java if else switch 编辑:程序博客网 时间:2024/06/01 12:36
public class StudentDaoImpl implements StudentDao {private String url = "src/student.xml";/* * <student idcard="111" examid="222"> <name>张三</name> * <location>长沙</location> <grade>89</grade> </student> "src/student.xml" *//** * 添加学生 *  * @author luozehua */public void addStu(Student stu) {try {// 得到文档对象Document document = XmlUtils.getDocument(url);// 创建Student标签Element student = new Element("student");// 设置Student接点的属性student.setAttribute("idcard", stu.getIdcard());student.setAttribute("examid", stu.getExamid());// 创建name标签Element name = new Element("name");// 设置文本值name.setText(stu.getName());// 创建location标签Element location = new Element("location");// 设置文本值location.setText(stu.getLocation());// 创建grade标签Element grade = new Element("grade");// 设置文本值grade.setText(stu.getGrade() + "");// 将接点挂到Student下student.addContent(name);student.addContent(location);student.addContent(grade);// 获得文档的根节点Element rootNode = document.getRootElement();// 将Student挂到根节点上rootNode.addContent(student);XMLOutputter outputter = new XMLOutputter();outputter.output(document, new FileOutputStream(new File(url)));} catch (Exception e) {throw new RuntimeException(e);}}@SuppressWarnings("unchecked")public void delStu(String name) {Document document = null;try {document = XmlUtils.getDocument(url);Element rootElement = document.getRootElement();XPath path = XPath.newInstance("//exam/student");List<Element> studentList = path.selectNodes(rootElement);for (Element element : studentList) {String nameString = element.getChildText("name");System.out.println(element.getName());if (nameString.equalsIgnoreCase(name)) {element.getParentElement().removeContent(element);}}XMLOutputter outputter = new XMLOutputter();outputter.output(document, new FileOutputStream(new File(url)));} catch (Exception e) {e.printStackTrace();}}@SuppressWarnings("unchecked")public Student find(String examid) {Student student = null;try {Document document = XmlUtils.getDocument(url);Element rootElement = document.getRootElement();XPath path = XPath.newInstance("//exam/student");// 获得根节点下所有子节点,直接直接点List<Element> studengList = path.selectNodes(rootElement);for (Element element : studengList) {String examidstrStr = element.getAttributeValue("examid");if (examidstrStr.equals(examid)) {student = new Student();student.setExamid(element.getAttributeValue("examid"));student.setIdcard(element.getAttributeValue("idcard"));student.setName(element.getChildText("name"));student.setLocation(element.getChildText("location"));student.setGrade(Double.parseDouble(element.getChildText("grade")));}}} catch (JDOMException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return student;}}