XML 文件的读写操作

前端之家收集整理的这篇文章主要介绍了XML 文件的读写操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
XMLWriter write=null; SAXReader reader =new SAXReader(); OutputFormat format =OutputFormat.createPrettyPrint(); format.setEncoding("GBK"); String filePath="d:\\Server.xml"; File file = new File(filePath); if(file.exists()) { try { Document document = reader.read(file); Element root =document.getRootElement(); boolean bl=false; for (Iterator i=root.elementIterator("学生");i.hasNext();) { Element Student =(Element)i.next(); if(Student.attributeValue("sid").equals("001")) { Student.selectSingleNode("姓名:").setText("王五"); Student.selectSingleNode("年龄:").setText("25"); try { write = new XMLWriter(new FileWriter(filePath),format); write.write(document); write.close(); bl=true; break; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bl) { Element student =root.addElement("学生"); student.addAttribute("sid","100"); Element sid =student.addElement("编号"); sid.setText("100"); Element name =student.addElement("姓名"); name.setText("行行行"); Element sex =student.addElement("性别"); sex.setText("男"); Element age =student.addElement("编号"); age.setText("25"); try { write = new XMLWriter(new FileWriter(filePath),format); write.write(document); write.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { Document _document =DocumentHelper.createDocument(); Element _root =_document.addElement("学生信息"); Element _student=_root.addElement("学生"); _student.addAttribute("sid","100"); Element _sid =_student.addElement("编号"); _sid.setText("100"); Element _name =_student.addElement("姓名"); _name.setText("行行行002"); Element _sex =_student.addElement("性别"); _sex.setText("男"); Element _age =_student.addElement("编号"); _age.setText("25"); try { write = new XMLWriter(new FileWriter(filePath),format); write.write(_document); write.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("结束操作!!!"); 原文链接:https://www.f2er.com/xml/299855.html

猜你在找的XML相关文章