比如在c盘下已存在info.xml文件
<root>
<student>
<name...>
...
</student>
</root>
如何用sax在这个xml添加student节点?
------解决方案--------------------
- Java code
//写入XML private void writeXML(Document doc) { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); try { XMLWriter writer = new XMLWriter(new FileOutputStream("C:\\info.xml"), format); writer.write(doc); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //添加管理员 public void insert(Student student) throws Exception { Document doc = this.readXML(); Element root = doc.getRootElement(); Element studentElement = root.addElement("student"); Element studentNameElement = studentElement .addElement("name"); usernameElement.addText(student.getStudentName()); Element passwordElement = studentElement .addElement("password"); passwordElement.addText(student.getPassword()); .... this.writeXML(doc); } }
------解决方案--------------------
- Java code
//读取XML private Document readXML() throws Exception { SAXReader reader = new SAXReader(); Document doc = reader.read(new File"C:\\info.xml")); return doc; }
------解决方案--------------------
SAX 不能用于添加节点