当前位置: 代码迷 >> J2EE >> 怎么在已存在的xml文件中用sax方法添加节点
  详细解决方案

怎么在已存在的xml文件中用sax方法添加节点

热度:79   发布时间:2016-04-22 01:56:45.0
如何在已存在的xml文件中用sax方法添加节点?
比如在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 不能用于添加节点
  相关解决方案