static Document document=null; static Element root-null; static Scanner input=new Scanner(System.in);
1.获取xml文件:
//创建解析器 SAXReader reader=new SAXReader(); try{ //读取xml文件 document=reader.read("xml相对路径"); //获取根节点 root=document.getRootElement(); }catch(DocumentException e){ e.printStackTrace(); }
2.
把内存中的保存到xml文档中
//创建输出流对象 XMLWriter writer=null; //设置格式化 OutputFormat format=null; format=OutputFormat.creatPrettyPrint(); try{ writer=new XMLWriter(new FileWriter("xml文件相对路径"),format) //真正的写入 writer.write(document); }catch (IOException e) { e.printStackTrace(); }finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } }
3.查看全部xml内容
Iterator<Element> books=rootNode.elementIterator(); //遍历 while(books.hasNext()){ Element book = books.next(); System.out.println("图书编号是:"+book.attributeValue("id")); //通过图书编号获取图书名称 Iterator<Element> bookName = book.elementIterator(); //遍历图书信息 while(bookName.hasNext()){ Element bookz = bookName.next(); System.out.println("图书id------>"+bookz.attributeValue("id")); System.out.println("图书型号------ >"+bookz.attributeValue("name")); if(!bookz.getTextTrim().equals("")){ System.out.println("图书名称是:"+bookz.getTextTrim()); } } }
4.删除节点
//遍历整个dom 找到需要删除的节点 Iterator<Element> books = rootNode.elementIterator(); System.out.println("请输入要删除的bookId"); String id=input.next(); while(books.hasNext()){ Element bookName = books.next(); if(bookName.attributeValue("id").equals(id)){ rootNode.remove(bookName); } }
5.修改节点
//遍历整个dom 找到需要修改的节点 Iterator<Element> books = rootNode.elementIterator(); System.out.println("请输入要修改的图书id:"); String id=input.next(); System.out.println("请输入修改后的id:"); String ids=input.next(); while(books.hasNext()){ Element bookName = books.next(); if(bookName.attributeValue("id").equals(id)){ bookName.setAttributeValue("id",ids); } }
6.添加节点
//先从book根节点创建子节点 System.out.println("请输入bookId的id:"); String bid=input.next(); Element bookId=rootNode.addElement("bookId"); bookId.addAttribute("id",bid); System.out.println("请输入bookName的id:"); String id=input.next(); System.out.println("请输入bookName的name:"); String name=input.next(); System.out.println("请输入bookName的值:"); String values=input.next(); Element bookName=bookId.addElement("bookName"); bookName.addAttribute("id",id); bookName.addAttribute("name",name); bookName.addText(values);